Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
362 views
in Technique[技术] by (71.8m points)

javascript - 如何使用jQuery将事件附加到动态HTML元素? [重复](How do I attach events to dynamic HTML elements with jQuery? [duplicate])

This question already has an answer here:

(这个问题已经在这里有了答案:)

Suppose I have some jQuery code that attaches an event handler to all elements with class .myclass .

(假设我有一些jQuery代码,将事件处理程序附加到所有类为.myclass元素上。)

For example:

(例如:)

$(function(){
    $(".myclass").click( function() {
        // do something
    });
});

And my HTML might be as follows:

(我的HTML可能如下所示:)

<a class="myclass" href="#">test1</a>
<a class="myclass" href="#">test2</a>
<a class="myclass" href="#">test3</a>

That works with no problem.

(没问题。)

However, consider if the .myclass elements were written to the page at some future time.

(但是,请考虑是否在将来某个时间将.myclass元素写入页面。)

For example:

(例如:)

<a id="anchor1" href="#">create link dynamically</a>
<script type="text/javascript">
$(function(){
    $("#anchor1").click( function() {
        $("#anchor1").append('<a class="myclass" href="#">test4</a>');
    });
});
</script>

In this case, the test4 link is created when a user clicks on a#anchor1 .

(在这种情况下,当用户单击a#anchor1时将创建test4链接。)

The test4 link does not have the click() handler associated with it, even though it has class="myclass" .

(尽管test4链接具有class="myclass" ,但它没有与click()处理函数关联的内容。)

Basically, I would like to write the click() handler once and have it apply to both content present at page load, and content brought in later via AJAX / DHTML .

(基本上,我想编写一次click()处理函数,并将其应用于页面加载时出现的内容以及以后通过AJAX / DHTML引入的内容。)

Any idea how I can fix this?

(知道我该如何解决吗?)

  ask by frankadelic translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

Please log in or register to answer this question.

Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...