jQuery点击不适用于动态创建的项目 [英] jQuery click not working for dynamically created items

查看:71
本文介绍了jQuery点击不适用于动态创建的项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一段jQuery,它可以遍历给定div中的每个元素( #container ),并在每次点击一个范围时执行javascript警报。如果< span> 的是静态的,这可以正常工作。

然而,如果我使用一块代码如:

  $(someLink).click(function(){
$(#container)。 html(<具有新跨度的新html>)
});

jQuery代码不会触发。奇怪的是,虽然



我的问题是:我的Click事件不适用于动态创建的项目吗?我假设我将不得不添加一些东西到我的文档准备好或心跳脚本(每100毫秒触发一次)来连接事件。

解决方案 $ p
$ b

  $('#wrapper').on('click','a' ,function(){...}); 

其中 #wrapper 是一个静态元素你添加了动态链接。



所以,你有一个硬编码到HTML源代码的包装器:

 < div id =wrapper>< / div> 

,然后用动态内容填充它。我们的想法是将事件委托给该包装器,而不是直接在动态元素上绑定处理程序。






Btw,I推荐 Backbone.js - 它为这个过程提供了结构:

 var YourThing = Backbone.View.extend({

//静态包装(事件委托的根)
el:$('#wrapper '),

//这里定义了事件绑定
事件:{
'点击':'anchorClicked'
},

//你的DOM事件处理程序
anchorClicked:function(){
//句柄点击事件
}

});

new YourThing; //初始化你的东西


I have a piece of jQuery that loops through each element in a given div( #container) and does a javascript alert each time a span is clicked. This works fine if the <span>'s are static.

However, if I use a piece of code like:

$(someLink).click(function(){
   $("#container").html( <new html with new spans> )
});

The jQuery code doesn't fire off. Oddly enough though

My question is : Is there a reason my Click events don't work for dynamically created items? I assume I will have to add something into my document ready or heartbeat-script (which is fired every 100 miliseconds) to hook up the events??

解决方案

Do this:

 $( '#wrapper' ).on( 'click', 'a', function () { ... });

where #wrapper is a static element in which you add the dynamic links.

So, you have a wrapper which is hard-coded into the HTML source code:

<div id="wrapper"></div>

and you fill it with dynamic content. The idea is to delegate the events to that wrapper, instead of binding handlers directly on the dynamic elements.


Btw, I recommend Backbone.js - it gives structure to this process:

var YourThing = Backbone.View.extend({

    // the static wrapper (the root for event delegation)
    el: $( '#wrapper' ),

    // event bindings are defined here 
    events: {
        'click a': 'anchorClicked'
    },

    // your DOM event handlers
    anchorClicked: function () {
        // handle click event 
    }

});

new YourThing; // initializing your thing

这篇关于jQuery点击不适用于动态创建的项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆