jQuery를 사용하여 요소를 선택하려면 어떻게해야합니까? (기간) 아이디?
다음과 같은 클래스 및 컨트롤러 작업 방법이 제공됩니다.
public School
{
public Int32 ID { get; set; }
publig String Name { get; set; }
public Address Address { get; set; }
}
public class Address
{
public string Street1 { get; set; }
public string City { get; set; }
public String ZipCode { get; set; }
public String State { get; set; }
public String Country { get; set; }
}
[Authorize(Roles = "SchoolEditor")]
[AcceptVerbs(HttpVerbs.Post)]
public SchoolResponse Edit(Int32 id, FormCollection form)
{
School school = GetSchoolFromRepository(id);
UpdateModel(school, form);
return new SchoolResponse() { School = school };
}
그리고 다음과 같은 형태 :
<form method="post">
School: <%= Html.TextBox("Name") %><br />
Street: <%= Html.TextBox("Address.Street") %><br />
City: <%= Html.TextBox("Address.City") %><br />
Zip Code: <%= Html.TextBox("Address.ZipCode") %><br />
Sate: <select id="Address.State"></select><br />
Country: <select id="Address.Country"></select><br />
</form>
School 인스턴스와 학교의 Address 멤버를 모두 업데이트 할 수 있습니다. 이것은 꽤 좋다! ASP.NET MVC 팀 감사합니다!
그러나 jQuery를 사용하여 드롭 다운 목록을 선택하여 미리 채울 수 있습니까? 이 서버 측을 수행 할 수는 있지만 페이지에 목록에 영향을 미치는 다른 동적 요소가 있음을 알고 있습니다.
다음은 내가 지금까지 가지고 왔으며 선택기가 ID와 일치하지 않는 것처럼 작동하지 않습니다.
$(function() {
$.getJSON("/Location/GetCountryList", null, function(data) {
$("#Address.Country").fillSelect(data);
});
$("#Address.Country").change(function() {
$.getJSON("/Location/GetRegionsForCountry", { country: $(this).val() }, function(data) {
$("#Address.State").fillSelect(data);
});
});
});
에서 Google 그룹스 :
각 특수 문자 앞에 두 개의 백 슬래시를 사용하십시오.
A backslash in a jQuery selector escapes the next character. But you need two of them because backslash is also the escape character for JavaScript strings. The first backslash escapes the second one, giving you one actual backslash in your string - which then escapes the next character for jQuery.
So, I guess you're looking at
$(function() {
$.getJSON("/Location/GetCountryList", null, function(data) {
$("#Address\\.Country").fillSelect(data);
});
$("#Address\\.Country").change(function() {
$.getJSON("/Location/GetRegionsForCountry", { country: $(this).val() }, function(data) {
$("#Address\\.State").fillSelect(data);
});
});
});
Also check out How do I select an element by an ID that has characters used in CSS notation? on the jQuery FAQ.
You can't use a jQuery id selector if the id contains spaces. Use an attribute selector:
$('[id=foo bar]').show();
If possible, specify element type as well:
$('div[id=foo bar]').show();
Escape it for Jquery:
function escapeSelector(s){
return s.replace( /(:|\.|\[|\])/g, "\\$1" );
}
usage example:
e.find('option[value='+escapeSelector(val)+']')
more info here.
The Release Candidate of ASP.NET MVC that was just released fixed this issue, it now replaces the dots with underscores for the ID attribute.
<%= Html.TextBox("Person.FirstName") %>
Renders to
<input type="text" name="Person.FirstName" id="Person_FirstName" />
For more information view the release notes, starting on page 14.
This is documented in jQuery Selectors docs:
To use any of the meta-characters (such as
!"#$%&'()*+,./:;<=>?@[\]^`{|}~) as a literal part of a name, it must be escaped with with two backslashes:\\. For example, an element withid="foo.bar", can use the selector$("#foo\\.bar").
In short, prefix the . with \\ as follows:
$("#Address\\.Country")
Why doesn't . work in my ID?
The problem is that . has special significance, the string following is interpreted as a class selector. So $('#Address.Country') would match <div id="Address" class="Country">.
When escaped as \\., the dot will be treated as normal text with no special significance, matching the ID you desire <div id="Address.Country">.
This applies to all the characters !"#$%&'()*+,./:;<=>?@[\]^`{|}~ which would otherwise have special significance as a selector in jQuery. Just prepend \\ to treat them as normal text.
Why 2 \\?
As noted in bdukes answer, there is a reason we need 2 \ characters. \ will escape the following character in JavaScript. Se when JavaScript interprets the string "#Address\.Country", it will see the \, interpret it to mean take the following character litterally and remove it when the string is passed in as the argument to $(). That means jQuery will still see the string as "#Address.Country".
That's where the second \ comes in to play. The first one tells JavaScript to interpret the second as a literal (non-special) character. This means the second will be seen by jQuery and understand that the following . character is a literal character.
Phew! Maybe we can visualize that.
// Javascript, the following \ is not special.
// |
// |
// v
$("#Address\\.Country");
// ^
// |
// |
// jQuery, the following . is not special.
Using two Backslashes it´s ok, it´s work. But if you are using a dynamic name, I mean, a variable name, you will need to replace characters.
If you don´t wan´t to change your variables names you can do this:
var variable="namewith.andother";
var jqueryObj = $(document.getElementById(variable));
and than you have your jquery object.
Just additional information: Check this ASP.NET MVC issue #2403.
Until the issue is fixed, I use my own extension methods like Html.TextBoxFixed, etc. that simply replaces dots with underscores in the id attribute (not in the name attribute), so that you use jquery like $("#Address_Street") but on the server, it's like Address.Street.
Sample code follows:
public static string TextBoxFixed(this HtmlHelper html, string name, string value)
{
return html.TextBox(name, value, GetIdAttributeObject(name));
}
public static string TextBoxFixed(this HtmlHelper html, string name, string value, object htmlAttributes)
{
return html.TextBox(name, value, GetIdAttributeObject(name, htmlAttributes));
}
private static IDictionary<string, object> GetIdAttributeObject(string name)
{
Dictionary<string, object> list = new Dictionary<string, object>(1);
list["id"] = name.Replace('.', '_');
return list;
}
private static IDictionary<string, object> GetIdAttributeObject(string name, object baseObject)
{
Dictionary<string, object> list = new Dictionary<string, object>();
list.LoadFrom(baseObject);
list["id"] = name.Replace('.', '_');
return list;
}
I solved the issue with the solution given by jquery docs
My function:
//funcion to replace special chars in ID of HTML tag
function jq(myid){
//return "#" + myid.replace( /(:|\.|\[|\]|,)/g, "\\$1" );
return myid.replace( /(:|\.|\[|\]|,)/g, "\\$1" );
}
Note: i remove the "#" because in my code i concat the ID with another text
'Programming' 카테고리의 다른 글
| 리플렉션을 통해 Java 클래스가 추상적인지 여부를 어떻게 확인할 수 있습니까? (0) | 2020.05.24 |
|---|---|
| 빌드 계획을 계산할 수 없습니다 : 플러그인 org.apache.maven.plugins : maven-resources-plugin : 2.5 또는 해당 종속성 중 하나를 해결할 수 없습니다 (0) | 2020.05.24 |
| 서브 클립 스 svn : ignore (0) | 2020.05.24 |
| Ruby on Rails에서 setter 메소드를 재정의하는 올바른 방법은 무엇입니까? (0) | 2020.05.24 |
| "일등석"개체 란 무엇입니까? (0) | 2020.05.23 |