-1

我正在使用 jQuery 向 php 页面添加动态内容。添加内容我没有问题我似乎无法找到使新内容响应点击事件的方法。

例如(我在这里使用 div 但可能是按钮或其他类型)。

$("#oldstuff").after('<div id="newstuff">Some content that should respond to click event</div>');

编辑:我目前使用的是 jquery 1.9.1,我使用的是 1.6.2,但我正在检查需要更新的 jquery 版本的 magnific-popup。

我没有发布我失败的尝试(

 $("#newstuff").click(function() {...
 $("#newstuff").live('click', function() {...
 binding the click event, etc.

因为我认为我遗漏了一些基本的东西,一个更老练的 jQuery 用户会发现而没有代码损坏的噪音。

4

5 回答 5

4

您可以在将元素插入 DOM之前附加单击事件:

$('<div id="newstuff">...</div>').click(function(){ 
  //do something 
}).insertAfter('#oldstuff');
于 2013-07-27T04:42:43.107 回答
1

似乎找不到让新内容响应点击事件的方法。

你必须做事件委托

$("#oldstuff").on("click", '#newstuff',function(){
alert( $(this).text() );
});
于 2013-07-27T04:42:56.350 回答
0

您需要将事件附加到父元素。

HTML:

<div id="parent">
    <div class="thediv">Hello</div>
</div>

JavaScript:

function addDiv() {
    var div = document.createElement('div');
    div.className = 'thediv';
    document.getElementById('parent').appendChild(div);
}

$('#parent').on('click', '.thediv', function() {
    // ...
});

看看这种技术是否有效。

于 2013-07-27T05:40:01.713 回答
-1

可能是您在附加 DOM 之前绑定事件,并且在最新版本的 jquery 库中,live 方法已被弃用,因此即使在附加 DOM 之后也尝试绑定单击,或者您可以使用以下代码...

首先添加 DOM。

    $("#oldstuff").after('<div id="newstuff">Some content that should respond to click event</div>');

然后绑定事件。

    $('#newstuff').on('click',function(){alert('do your stuff!')}); 

或者

    $('#newstuff').click(function(){alert('do your stuff!')}); 
于 2013-07-27T07:34:38.783 回答
-2

尝试这个

$("#yourElementId").live("click",function(){
  alert( $(this).text() );
 });

.click加载 dom 或动态创建的元素后无法正常工作

于 2013-07-27T04:46:51.637 回答