单击新添加的链接不执行javascript函数

单击新添加的链接不执行javascript函数

本文介绍了单击新添加的链接不执行javascript函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在尝试jquery时,我创建了html和javascript.

while experimenting with jquery, I created this html and javascript.

<body>
<div id="results">
<div class="mylinkdiv">
<a class="mylinkclass" href="#">8</a>
: This is supposed to be a toaster.
<br>
<a class="mylinkclass" href="#">14</a>
: with a toaster maybe.
<br>
<a class="mylinkclass" href="#">51</a>
: If we're really creative.
<br>

</div>
</div>
<button id="remove" type="button" > Remove</button>
<button id="add" type="button" > Add</button>

</body>

javascript具有弹出包含链接文本的消息的功能,还具有向div添加一些链接的功能.名为remove的函数将删除内部div.

the javascript has a function to popup a message containing the link text.It also has a function to add some links to the div .A function named remove which removes the inner div .

$(document).ready(function(){
    $('.mylinkclass').click(function(){
           getLinkText(this);
        });

    $('#remove').click(function(){
           removeContents();
        });

     $('#add').click(function(){
           addContents();
        });
});

function getLinkText(that){
    var txt = $(that).text();
    var num = parseInt(txt);
    alert('num='+num);
    return false;
}

function addContents(){
  $('#results').append('<a class="mylinkclass" href="#">70</a>  new line1 <br>');
  $('#results').append('<a class="mylinkclass" href="#">77</a> new line2<br>');
}

function removeContents(){
  $('.mylinkdiv').remove();
}

当我单击原始html页面中的链接(即3个链接)时,弹出警告框.

When I click on the links in the original html page ( ie the 3 links ) ,the alert box pops up.

当我单击添加按钮时,它会向div添加两个新链接.但是,当我单击这些新添加的链接时,警报不会弹出!

When I click the add button,it adds two new links to the div.But,when I click on those newly added links ,the alert does not pop up!

我不明白为什么..有人可以告诉我吗?

I can't understand why..can someone tell me?

推荐答案

如果使用jQuery 1.7,请使用.on;如果使用jQuery 1.6,请使用.delegate.

Use .on if you are using jQuery 1.7 or .delegate if you are using jQuery 1.6

jQuery('#results').on('click','.mylinkclass',function() {
    getLinkText(this);
});

演示

执行此操作的另一种方法是克隆现有元素演示

Another way you can do this is you clone your existing element, Demo

var cloned = jQuery('.mylinkclass:last').clone(true);
jQuery('#results').append(cloned);

在第二种情况下,事件监听器也将被复制,您无需使用.on或.delegate.

In the second case event listener will also be copied and you dont need to use .on or .delegate.

这篇关于单击新添加的链接不执行javascript函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 09:33