JQuery无法找到选择列表

时间:2013-12-17 10:42:15

标签: javascript jquery

对于我的生活,我不能解决为什么JQuery无法在此代码中找到选择列表。我尝试在几个JQuery测试页面中访问Select元素,它似乎总是很好,但这只是没有做任何事情:

<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>

2 个答案:

答案 0 :(得分:4)

更改

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

 <select id='activity_1'><

您的选择器$('#activity')搜索ID为“activity”而不是“#activity”的元素

答案 1 :(得分:0)

你需要使用两个反斜杠来逃避冒号:

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

也替换下面。

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

编辑:

  

如果你想使用任何元字符(例如!“#$%&amp;'()* +,。/:;&lt; =&gt;?@ [] ^`{|}〜)作为名称的字面部分,您必须使用两个反斜杠转义字符:。例如,如果您有一个id =“#foobar”的元素,则可以使用选择器$(“#\#foobar”)。 W3C CSS规范包含完整的。

Jquery selector API Reference

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