如何将 jQuery 绑定到一个链接 <a> 到一个 onclick 函数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/712851/
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
How to bind jQuery to ONE link <a> to an onclick function?
提问by Gath
How do I bind a function using jQuery to oneand only one link label in my HTML document which has several links?
如何使用 jQuery 将一个函数绑定到我的 HTML 文档中一个且只有一个链接标签,其中有多个链接?
My code looks like this;
我的代码看起来像这样;
$("a").click(function(){
$("#login").slidedown("slow");
});
But this binds all the links in the document.
但这绑定了文档中的所有链接。
回答by Jeremy B.
To expand on Michael, you'll want to add a return false;
要扩展 Michael,您需要添加 return false;
$("#clicked_link").click(function(){
$("#login").slidedown("slow");
return false;
});
Otherwise when you click the link the browser will still attempt to follow the link and you'll lose the javascript action.
否则,当您单击该链接时,浏览器仍会尝试跟随该链接,而您将丢失 javascript 操作。
回答by Michael
Name your anchor/link that has the click event with an id attribute.
使用 id 属性命名具有点击事件的锚点/链接。
So for instance:
所以例如:
<a href="..." id="clicked_link">...</a>
And then use the following jquery statement:
然后使用以下 jquery 语句:
$("#clicked_link").click(function(){ $("#login").slidedown("slow"); });
Easy as pie!
非常简单!