Javascript 锚定标签 jQuery 单击
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8551213/
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
Anchor tag jQuery Click
提问by Suave Nti
I have an Anchor Tag like this
我有一个这样的锚标签
<a href="javascript:anchorScr()" id="anch1" class ="af-link"/>
It is taking me two clicks on the anchor tag to respond to the javascript function anchorScr();
我需要在锚标记上单击两次才能响应 javascript 函数 anchorScr();
function anchorScr() {
jQuery('a').click(function (event) {
var id = $(this).attr("id");
alert(id);
});
}
Am I doing something wrong? Why my anchorScr() is not called on the first click ?
难道我做错了什么?为什么我的 anchorScr() 在第一次点击时没有被调用?
回答by Oded
This calls the anchorScr
function when the anchor is clicked:
anchorScr
单击锚点时调用该函数:
href="javascript:anchorScr()"
The function then attaches a click
event handler to all a
elements.
然后该函数将一个click
事件处理程序附加到所有a
元素。
Remove the href
and just have this:
删除href
并只有这个:
jQuery('a').click(function (event) {
var id = $(this).attr("id");
alert(id);
});
The code will execute - attaching the click
event handler to all a
elements. You should probably only run this on ready()
to ensure that the page has fully loaded into the DOM.
代码将执行 - 将click
事件处理程序附加到所有a
元素。您可能应该只运行它ready()
以确保页面已完全加载到 DOM 中。
回答by dku.rajkumar
<a href="#" id="anch1" class ="af-link">click here</a>
jQuery(document).ready(function(){
jQuery('a').click(function (event) {
var id = $(this).attr("id");
alert(id);
});
});