Javascript 使用 JQuery 将 onclick 属性添加到 <a> 标签

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3389792/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 04:24:30  来源:igfitidea点击:

Adding onclick Attribute to <a> tag using JQuery

javascriptjquery

提问by Joseph Ghassan

I have a link button that I want to change it onclickcallback function when clicked:

我有一个链接按钮,我想onclick在单击时更改它的回调函数:

I am using .attr()to change the onclickevent but it simply doesn't work.

我正在使用.attr()更改onclick事件,但它根本不起作用。

$('#' + test).text('Unlike');
$('#' + test).attr("onclick", "return deleteLikeComment('"
        + CommentsWrapper + "','" + activityID + "', '" + test + "');");

But it simply doesn't work.

但这根本行不通。

I just want to switch the callback method when the link is clicked.

我只想在点击链接时切换回调方法。

回答by spinon

Why are you attaching the event with an attr?

你为什么用 attr 附加事件?

Why not just do like so:

为什么不这样做:

$('#' + test).bind("click", function()
{
    //functionality that you were trying to add using attr can now go inside here.
});

回答by fearofawhackplanet

$('#' + test).click(function() {
    return deleteLikeComment(...);
}); 

回答by Jason

Use "click()" instead of attr()

使用“ click()”代替attr()

回答by Felix Kling

If you want to switch the callback method every time the link is clicked, use .toggle(). It alternates between the two provided functions.

如果要在每次点击链接时切换回调方法,请使用.toggle(). 它在提供的两个功能之间交替。