Jquery / Javascript:使用javascript动态添加的按钮不起作用 [英] Jquery/Javascript: Buttons added dynamically with javascript do not work

查看:203
本文介绍了Jquery / Javascript:使用javascript动态添加的按钮不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个html代码块:

I have a code chunk of html:

<div id="chunk-1" class="chunk">  
    <div class="chunkText">Text<div>  
    <button class="addChunk">Click Me</button>  
</div>

<script>

$(".addChunk").click(function(){create_chunk(this.parentNode)})

function create_chunk(after_this){
    $(after_this).after(chunk_html)
    var i = 0
    $("div.chunk").each(function(){$(this).attr('id', "chunk-" + i++)})
    }

</script>

现在,这可以工作,但只能在页面上静态呈现的.chunk。当我按下按钮时,出现第二个块,但该按钮不起作用。如果我添加了两个或更多块要呈现的html,每一个都可以使用,但是它创建的块的按钮不是。我应该怎么做?

Now, this works, but only for the .chunk that is statically rendered on the page. When I press the button a second chunk appears, but that button does not work. If I add the html for two or more chunks to be rendered, each one works, but the buttons for the chunks it creates do not. What should I do?

推荐答案

下面的事件处理程序在添加时将click事件附加到与选择器匹配的元素处理程序。

The event handler in the below line attaches the click event to the element matching the selector when you add the handler.

$(".addChunk").click(function(){create_chunk(this.parentNode)})

您可以使用现场处理程序执行此操作。以下代码将解决您的问题

you can use the live handler to do this. the following code will solve your problem

$(".addChunk").live('click'. function(){create_chunk(this.parentNode)});

这篇关于Jquery / Javascript:使用javascript动态添加的按钮不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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