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

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

Anchor tag jQuery Click

javascriptjqueryanchor

提问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 anchorScrfunction when the anchor is clicked:

anchorScr单击锚点时调用该函数:

href="javascript:anchorScr()"

The function then attaches a clickevent handler to all aelements.

然后该函数将一个click事件处理程序附加到所有a元素。

Remove the hrefand just have this:

删除href并只有这个:

jQuery('a').click(function (event) {
    var id = $(this).attr("id");
    alert(id);
});

The code will execute - attaching the clickevent handler to all aelements. 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);
   });
});