例如,我有这样的代码:
$("#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.因为我的表单上将有很多删除链接,但我有一个问题,在这种情况下,如何将任何参数传递给单击函数?
发布于 2011-07-28 20:32:36
试着做这样的事情:
//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发布于 2011-07-28 20:31:42
你可以用几种方法来做,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>");以及使用集合分配或链接等的其他方式。
发布于 2011-07-28 20:33:00
$("#total").html(
$("Price $<span>" + value + "</span>").append(
$("<a id='remove' href='#'>remove</a>").click(function(){
// Click Handler
})
)
);https://stackoverflow.com/questions/6865267
复制相似问题