[英]How to add onclick event to dynamic a href with jquery
例如我有这样的代码:
$("#total").html("Price $<span>" + value + "</span>");
我也想在那里添加一个href按钮
$("#total").html("Price $<span>" + value + "</span><a id='remove' href='#'>remove</>);
但是我如何为该href添加onclick
事件?
UPDATE
我真的很喜欢这种解决方案:
//Create the link to remove the item beforehand, and add the onclick event handler.
var removeLink = $("<a id='remove' href='#'>remove</a>").click(function(e) {
//Click event handler here.
});
$("#total").html("Price $<span>" + value + "</span>"); //Create the price value
$("#total").append(removeLink); //Add the remove link.
因为我的表单上会有很多删除链接,但是在这种情况下我有一个疑问如何将任何参数传递给该click函数?
尝试这样的事情:
//Create the link to remove the item beforehand, and add the onclick event handler.
var removeLink = $("<a id='remove' href='#'>remove</a>").click(function(e) {
//Click event handler here.
});
$("#total").html("Price $<span>" + value + "</span>"); //Create the price value
$("#total").append(removeLink); //Add the remove link.
它比一个衬里还要冗长一些,但是在我看来,它非常可读。
为了回应您在下面的评论,如果您想传递参数,可以采用多种方法。 由于您使用的是Jquery,因此我可以想到两种主要方法:
方法1:利用匿名函数能够访问外部作用域中的变量
var param = 1234; // <-- We know this value before we create the link
var removeLink = $("<a id='remove' href='#'>remove</a>").click(function(e) {
var someVariable = param + 4321;
alert(someVariable); //Shows "5555" in a message box when link is clicked.
});
方法2:使用jQuery.data
var param = 1234; // <-- We know this value before we create the link
var removeLink = $("<a id='remove' href='#'>remove</a>").click(function(e) {
var someVariable = jQuery.data(this, 'param') + 4321;
alert(someVariable); //Shows "5555" in a message box when link is clicked.
});
jQuery.data(removeLink, 'param', param); // <-- Save the param as a Jquery data value
您可以通过几种方法来做到这一点, live()
是一个示例,或者..
$("#total").html("Price $<span>" + value + "</span><a id='remove' href='#'>remove</a>");
$("#remove").click(function() { /* ... */ });
要么
$("#total").html("Price $<span>" + value + "</span><a id='remove' onclick='doSomething();' href='#'>remove</a>");
以及使用集合分配或链接等的其他方式
$("#total").html(
$("Price $<span>" + value + "</span>").append(
$("<a id='remove' href='#'>remove</a>").click(function(){
// Click Handler
})
)
);
您应该可以通过使用简单的JQuery 查找功能并单击处理程序来执行此操作:
var h = $("#total").html("<span>Price $<span>" + value + "</span><a id='remove' href='#'>remove<a/></span>");
h.find('a').click(function() { alert('hello') });
您可以使用链接尝试
$("#total").html("Price $<span>" + value + "</span><a id='remove' href='#'>remove</>).find(">a").click(function(){
//on click code goes here
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.