Javascript 如何使jQuery即使在尚未创建的对象上也能工作?

Javascript 如何使jQuery即使在尚未创建的对象上也能工作?,javascript,jquery,Javascript,Jquery,可能重复: 有没有办法更改以下代码: $('#city') .focus(function () { $('option[value="99"]', this).remove(); store.setItem($(this).attr('id'), $(this).val()); }) .change(function () { store.setItem($(this).a

可能重复:

有没有办法更改以下代码:

$('#city')
        .focus(function () {
            $('option[value="99"]', this).remove();
            store.setItem($(this).attr('id'), $(this).val());
        })
        .change(function () {
            store.setItem($(this).attr('id'), $(this).val());
            $(this).attr("title", $("option:selected", this).attr("title"));
            $('#detailData').html("");
        });
因此,它适用于选择,即使它们尚未创建,只要它们具有类“更新标题”。例如:

<select class="update-title"> 


我看到一些使用live的实现,但有人说它不适合使用。这样做的开销也很大。在我确定已使用document.ready()创建了选择之后,是否最好添加代码?

请查看。这是对
live
的替换,它将为您完成此操作。

是的,您确定已使用document.ready()创建选择,如果html未加载到ajax中,您需要:


这样,
文档
将侦听在
上触发的任何事件。更新title
元素,无论它们是否在文档加载时存在。

最好的方法是使用委托-因此您将事件处理程序绑定到加载dom时存在的父元素-它将依次侦听给定元素上的事件并处理它们

使用jQuery1.7的ex+

$('body').on('click','.update-title', function(){ // <-- all click events will now bubble
// up to body - and it will listen for events from .update-title
    // code here
});

$('body')。on('click','.update title',function(){//类似于..@DanielA.White,从概念上讲,它们是相似的,但请注意,该问题的答案中没有一个建议使用
.on()
,这是该问题的最佳答案。
$('body').on('click','.update-title', function(){ // <-- all click events will now bubble
// up to body - and it will listen for events from .update-title
    // code here
});