简体   繁体   English

为什么此点击处理程序不能在JQuery中工作?

[英]Why doesn't this click handler work in JQuery?

I've got the following code in my page: 我的页面中有以下代码:

var offer_link = $('<a>').addClass('fc-offer-link');
offer_link.click(function() {
    alert('Hello');
});

offer_link.attr('href', "#" + this.id);
offer_link.append(this.subject);

this.list_item = $('<li>');
this.list_item.append(offer_link);

But even though the link appears on the page, the handler never gets called. 但是即使该链接出现在页面上,该处理程序也永远不会被调用。 What's going on? 这是怎么回事?

The problem turned out to be where the item got inserted into the DOM. 问题出在该项目插入DOM的地方。 It was being inserted using: 使用以下命令插入它:

$('#my_list').html(my_new_list.html())

It should have been using: 它应该一直在使用:

$('#my_list').replaceWith(my_new_list)

I think you just need to append the link to an element, like this: 我认为您只需要将链接附加到元素,如下所示:

<script type="text/javascript">
    $(function(){
        var link = $("<a>Click Me!</a>").addClass("fc-offer-link").appendTo($("#div1"));
        if (link){
            link.click(function(){
                alert("Hey there!");
            });  
        }   
    });
</script>
<div id="div1"></div>

EDIT : Not sure why I was downvoted, but here's a jsFiddle 编辑 :不知道为什么我被拒绝,但这是一个jsFiddle

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM