我怎样才能让jQuery即使在尚未创建的对象上也能工作

How can I make jQuery work even on objects not yet created?

本文关键字:创建 对象 工作 jQuery      更新时间:2023-09-26

可能的重复项:
在 jQuery 中绑定动态创建的元素

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

$('#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("");
        });

这样它就可以用于选择,即使它们尚未创建,只要它们具有类"update-title"。 例如:

<select class="update-title"> 

我看到一些使用live的实现,但有人说不好用。这样做也有很多开销。在我确定已使用 document.ready(( 创建选择后添加代码会更好吗?

看看on .这是live的替代品,可以为您执行此操作。

你需要

on

$(document).on('change', '.update-title', function(event){
    // your business here
});

这样,document侦听在.update-title元素上触发的任何事件,无论它们在文档加载时是否在那里。

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

exwith jQuery 1.7+

$('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
});

最佳做法是在 dom 加载时将事件处理程序绑定到最近的父级,因为您可以看到绑定到正文/文档的开销 - 所有单击事件都会冒泡 - 如果您绑定到父元素,则只有该元素内的那些会冒泡。

是的,如果 html 未在 ajax 中加载,您确定选择是使用 document.ready(( 创建的