繁体   English   中英

如何使用jQuery的replaceWith()函数使href链接触发函数?

[英]How can I use jQuery's replaceWith() function to make a href link trigger a function?

这是我尝试过的:

的HTML:

<div id="container">
  <p>a paragraph</p>
</div>
<button>replace with link</button>

脚本:

$(document).ready(function() {

     $("a.foo").click(function() {
        alert('hello world');
     });

     function foo() {
        alert('hello world');
     }

     $("button").click(function () {
        // neither of these work
        // $("#container p").replaceWith('<p><a href="#" class="foo" >trigger function<\/a><\/p>');
        // $("#container p").replaceWith('<p><a href="#" onclick="foo();return false" >trigger function<\/a><\/p>');
     });

});

我想你正在寻找live

http://docs.jquery.com/Events/live

取代这个

$("a.foo").click(function() {
        alert('hello world');
});

$("a.foo").live('click', function() {
        alert('hello world');
});

然后像

$("#container p").replaceWith('<p><a href="#" class="foo" >trigger function<\/a><\/p>');

为什么要使用.replaceWith() 您需要的只是.html()

$("button").click(function() {
  $("#container p").html('<p><a href="#" class="foo" >trigger function</a></p>');
});

始终记住,链接元素的href =“#”会导致回发,并且click事件可能无法正常工作。 在实时事件上,请单击“确定”,以防止产生默认操作。

$(".lnkLike").live("click", function (e){
   e.preventDefault();
});

暂无
暂无

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

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