jQuery选择JavaScript生成的元素

时间:2012-08-28 16:39:07

标签: javascript jquery

我正在使用JavaScript来动态生成一些HTML表格。在填写这个动态表之后,我使用jQuery来“抓取”一些输入并为表单验证做一些小的计算。但是,我的jQuery选择器不适用于动态HTML表单。谁能给我一些建议?谢谢!

以下是代码:

<script>
//generate HTML table
$('<tr><th><label for="id_CAM_1">Input:</label></th><td><select name="CAM_1_'+i+'" id="id_1_'+i+'"><option value="1">Option 1</option><option value="2">Option 2</option></select></td></tr>').appendTo('.table');

// jQuery selector, which does not work dynamically

$('select[name=CAM_1_'+i+']').change(function() {
            var ss1=$(this).val()
            alert(ss1)})
</script>

4 个答案:

答案 0 :(得分:1)

<script type="text/javascript">
    $(function() {
        $('<tr><th><label for="id_CAM_1">Input:</label></th><td><select name="CAM_1_'+i+'" id="id_1_'+i+'"><option value="1">Option 1</option><option value="2">Option 2</option></select></td></tr>')
            .appendTo('.table')
            .on('change', function() {
                alert(this.value);
        });
    });
</script>​​​​​​​​​​​​​​​

答案 1 :(得分:1)

以下内容将检测select

中名称以CAM_1_开头的所有tableSelector元素的所有更改
$('tableSelector').on('change', 'select[name^="CAM_1_"]', function() {
    alert(this.value);
});

答案 2 :(得分:1)

我想复制你的问题,但对我来说它完全正常。我确实必须添加右括号(})),因为这些似乎与您发布的内容不相符。你在控制台中得到任何错误吗?检查JavaScript控制台中是否有任何错误,以及您是否使用最新版本的jQuery。

<table class="table"></table>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.2.min.js"></script>
<script>
i = 0;
//generate HTML table
$('<tr><th><label for="id_CAM_1">Input:</label></th><td><select name="CAM_1_'+i+'" id="id_1_'+i+'"><option value="1">Option 1</option><option value="2">Option 2</option></select></td></tr>').appendTo('.table');

// jQuery selector, which does not work dynamically

$('select[name=CAM_1_'+i+']').change(function() {
    var ss1=$(this).val()
    alert(ss1)
});
</script>

答案 3 :(得分:0)

<script>
//generate HTML table
$('<tr><th><label for="id_CAM_1">Input:</label></th><td><select name="CAM_1_'+i+'"   id="id_1_'+i+'"><option value="1">Option 1</option><option value="2">Option 2</option></select></td></tr>').appendTo('.table');

// jQuery selector, which does not work dynamically

$('select[name=CAM_1_'+i+']').live("change",function() {
        var ss1=$(this).val()
        alert(ss1)})
</script>

所以基本上你需要使用jquery的live方法来动态生成html。