jquery - 如何使用jquery将onclick事件添加到动态a href

标签 jquery

例如我有这样的代码:

$("#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/

相关文章:

php - 是否可以使用 PHP 中的 cURL 或 Socket 函数确定最新的 jQuery 版本?

javascript - jQuery 类型函数作为变量

javascript - 在页面仍在加载时显示 JQuery slider

javascript - 使用 timepicker.js 时“timepicker 不是函数”?

javascript - 将文件上传到谷歌驱动器文件夹而不是用户浏览器javascript/jquery

javascript - Ajax 调用 MVC Controller - URL 问题

即使我删除类名,Jquery 元素悬停仍然有效

javascript - 如何格式化 Jon Leighton 的 jquery.date_input.pack 上的日期?

jquery - 如果屏幕窄于 1024px,则隐藏 DIV

javascript - 将片段附加到字符串