2013-12-17 25 views
0

對於我的生活,我無法弄清楚爲什麼JQuery無法在此代碼中找到選擇列表。我試圖訪問在幾個JQuery的測試頁面中選擇元素,它似乎總是不錯,但是這只是沒有做任何事情:JQuery無法查找選擇列表

<html> 
<head> 
    <script src="jquery.js"></script> 
    <script> 


    $(document).ready(function() { 
     var new_options = ['were filled with rocks', 'smelled like chicken pox', 'belonged to angry green crocs', 'are kept in a mouldy box' ]; 

     /* Remove all options from the select list */ 
     $("#activity_1").empty(); 

     /* Insert the new ones from the array above */  
     $.each(new_options, function(value) { 
     $("#activity_1").append($('<option>', {value: 'Testing', text : 'Testing'})); 
     }); 
    }); 
</script> 
</head> 
<body> 
    <select id='#activity_1'><option value='dud'>This shouldn't be here</option</select>, 
</body> 
</html> 
+1

請檢查您的標記的有效性。看起來'

+0

您的html中也有一個逗號(請參閱select後) –

回答

4

變化

<select id='#activity_1'>< 
     // ^

<select id='activity_1'>< 

您的選擇器$('#activity')搜索ID爲「activity」的元素不是「#activity」

+0

這正是問題所在。頭,見面。 –

0

您需要使用兩個回斜線逃脫冒號:

$("#\\#activity_1").empty(); 

替換下面也。

$.each(new_options, function(value) { 
    $("#\\#activity_1").append($('<option>', {value: 'Testing', text : 'Testing'})); 
}); 

編輯:!?

如果你希望使用任何的元字符(如「#$%&「()* +,/ :; < => @例如,如果你有一個id =「#foobar」的元素,你可以使用選擇器$( 「#\#foobar」)。W3C CSS規範包含完整內容。

Jquery selector API Reference

或者使用元素id,以便它不得包含任何元字符。