例如我有这样的代码:
$("#total").html("Price $<span>" + value + "</span>");
我还想在那里添加一个 href 按钮
$("#total").html("Price $<span>" + value + "</span><a id='remove' href='#'>remove</>);
但是我如何为该 href 添加 onclick
事件?
更新
我真的很喜欢这个解决方案:
//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.
因为我的表单上有很多删除链接,但我有一个问题,在这种情况下如何将任何参数传递给该点击函数?
最佳答案
尝试这样的事情:
//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,因此我可以立即想到两种主要方法:
方法一:利用匿名函数访问外部作用域中的变量
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
关于jquery - 如何使用jquery将onclick事件添加到动态a href,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6865267/