jQuery选择由php脚本生成的元素

时间:2012-12-22 01:57:09

标签: jquery regex

我的php脚本生成了多个<select id="direction_X"></select>。 X是它的ID。我试图通过这样做来选择这些元素:

$('select[id*="direction_"]').live('change', function() {
     selected = $('select[id*="direction_"] option:selected');
     option_ID = $(selected).val();

     console.log(option_ID);
}

事实上,当我使用时,我正在获取option_ID,但如果我尝试使用任何其他的,我将始终获得相同的option_ID。

如果您先点击,它会为您提供(空字符串),当您点击后,它会为您提供第一个

中的正确ID

2 个答案:

答案 0 :(得分:6)

您应该使用引用当前选择元素的this关键字。

$('select[id^="direction_"]').on('change', function() {
     var selected = $(this).val(); // this.value
     console.log(selected);
})

请注意,live方法已被弃用,您可以使用on方法,如果select元素是由php生成的,则不需要使用事件委托,以防后生成元素页面已加载,使用on方法委派事件的正确方法是:

$(document).on('change', 'select[id^="direction_"]', function() {

Attribute Starts With Selector | on

答案 1 :(得分:0)

好吧,如果你想获得所有选定的值,那么你将不得不遍历所有选择元素并构建一个包含所有选定选项的数组。

鉴于此HTML -

<select id="sel_1">
    <option value="1" selected="selected">1</option>
    ...
</select>
<select id="sel_2">
    <option value="2" selected="selected">2</option>
    ...
</select>
<select id="sel_3">
    ...
    <option value="3" selected="selected">3</option>
</select>

你会做这样的事情来收集所有选定的元素 -

var selValues = $("select[id*='sel'] option:selected").map(function(){
  return $(this).val();
});
console.log(selValues); // ["1", "2", "3"] 

Here is a quick demo (open your console)