在 jQuery 中按类名访问标记

access a tag by class name in jQuery

本文关键字:访问 jQuery      更新时间:2023-09-26

我通过jQuery创建了一些标签,并为其定义了一个类名,如下所示:

 $('#tr').html('<select class="optcode">
                 <option>select code</option>
                 <option>select code</option>'
              </select>);

在其他地方,我也想通过下面的代码按类名访问<select>但它不起作用,我该如何解决这个问题:

   $('.optcode').change(function(){
    alert('something');
})

尝试使用委托:-

$('#tr').on('change', '.optcode', function(){
    alert('something');
});

change 函数不绑定到元素,因为在执行代码时它们在 DOM 中不存在。 您可以使用函数同时将元素添加到 DOM 和绑定中。

这样的东西会起作用:

function doStuff() {
    $('#tr').html('<select class="optcode"><option>select code</option><option>select code</option></select>');
    $('.optcode').change(function(){
        alert('something');
    })
}
$(document).ready(function() {
    doStuff();
})

你可以看到它在这个JS小提琴中工作:https://jsfiddle.net/hsvnhhn7/

希望有帮助。

只是改变

$('#tr').html('<select class="optcode">
                 <option>select code</option>
                 <option>select code</option>'
              </select>);

$('#tr').html('<select class="optcode"><option>select code</option><option>select code</option></select>');

查看演示

$('#tr').html('<select class="optcode"><option>select code</option><option>select code</option></select>');
 $('.optcode').change(function(){
    alert('something');
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="tr"></div>