2008-12-08 13 views
161

鑑於以下類和控制器的操作方法:如何讓jQuery使用a選擇元素。 (期間)在他們的ID?

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> 

我能夠同時更新學校實例和學校的地址成員。這很好!謝謝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); 
    }); 
    }); 
}); 
+0

https://開頭學習。 jquery.com/using-jquery-core/faq/how-do-i-select-an-element-by-an-id-that-has-characters-used-in-css-notation/ – 2016-12-07 10:49:48

回答

268

Google Groups

Use two backslashes before each special character.

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.

所以,我猜你在看

$(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); 
    }); 
    }); 
}); 

也檢查了How do I select an element by an ID that has characters used in CSS notation?在jQuery常見問題。

+1

該死的你快!謝謝! – 2008-12-08 17:54:40

+4

我不知道什麼是合理化要求開發人員這樣做,它似乎是一個簡單的jQuery內啓發式的一套將解決這個問題,因爲沒有任何錯誤的ID與他們的週期... – 2009-03-24 22:46:10

+5

如果你didn不必逃避,你如何查詢ID地址和類狀態的元素(如果你知道該ID沒有通過指定類添加太多,但它應該仍然有效,我認爲)。 – bdukes 2009-03-25 13:12:07

0

只是附加信息: 檢查這ASP.NET MVC issue #2403

在問題解決之前,我使用自己的擴展方法(如Html.TextBoxFixed等),它只是用id屬性中的下劃線(不在名稱屬性中)替換點,以便使用jquery(如$(「 #Address_Street「),但在服務器上,它就像Address.Street。

示例代碼如下:

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; 
} 
9

ASP.NET MVC的候選版本剛發佈的修復了這個問題,現在用下劃線爲ID屬性替換點。

<%= Html.TextBox("Person.FirstName") %> 

呈現給

<input type="text" name="Person.FirstName" id="Person_FirstName" /> 

欲瞭解更多信息,請查看發行說明,從第14頁

21

如果id包含空格,則不能使用jQuery的ID選擇上。使用屬性選擇:

$('[id=foo bar]').show(); 

如果可能的話,指定元素類型,以及:

$('div[id=foo bar]').show(); 
2

使用兩個反斜線it's OK,it's工作。 但是,如果您使用動態名稱,我的意思是,一個變量名稱,您將需要替換字符。

如果您鴕鳥政策wan't改變你的變量名,你可以這樣做:

var variable="namewith.andother";  
var jqueryObj = $(document.getElementById(variable)); 

,比你有你的jQuery對象。

11

逃脫它的jQuery:

function escapeSelector(s){ 
    return s.replace(/(:|\.|\[|\])/g, "\\$1"); 
} 

使用示例:

e.find('option[value='+escapeSelector(val)+']') 

更多信息here

3

這是記錄在jQuery Selectors docs

To use any of the meta-characters (such as !"#$%&'()*+,./:;<=>[email protected][\]^`{|}~) as a literal part of a name, it must be escaped with with two backslashes: \\ . For example, an element with id="foo.bar" , can use the selector $("#foo\\.bar") .

總之,隨着\\前綴.如下:

$("#Address\\.Country") 

爲什麼我的ID不.工作?

問題是.具有特殊意義,下面的字符串被解釋爲類選擇器。所以$('#Address.Country')將匹配<div id="Address" class="Country">

當作爲\\.轉義時,該點將被視爲普通文本,沒有特別的意義,與您想要的ID相符<div id="Address.Country">

這適用於所有字符!"#$%&'()*+,./:;<=>[email protected][\]^`{|}~,否則這些字符在jQuery中作爲選擇器具有特殊意義。只要預先\\將它們視爲正常文本。

爲什麼2 \\

正如在bdukes回答中指出的那樣,我們需要2 \個字符。 \將在JavaScript中轉義以下字符。硒JavaScript時解釋字符串"#Address\.Country",它會看到\,把它解釋爲採取以下字符litterally刪除它時,字符串傳遞中作爲參數來$()。這意味着jQuery仍然會將該字符串視爲"#Address.Country"

這就是第二個\來玩的地方。第一個告訴JavaScript將第二個解釋爲文字(非特殊)字符。這意味着第二個將被jQuery看到,並且明白以下.字符是一個文字字符。

唷!也許我們可以想象這一點。

// Javascript, the following \ is not special. 
//   | 
//   | 
//   v  
$("#Address\\.Country"); 
//  ^
//   | 
//   | 
//  jQuery, the following . is not special. 
0

我解決了這個問題與jQuery的文檔中給出的解決方案

我的功能:

//funcion to replace special chars in ID of HTML tag 

function jq(myid){ 


//return "#" + myid.replace(/(:|\.|\[|\]|,)/g, "\\$1"); 
return myid.replace(/(:|\.|\[|\]|,)/g, "\\$1"); 


} 

注:我刪除了「#」,因爲在我的代碼與其他Concat的標識文字

字體: Jquery Docs select element with especial chars