最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Anchor tag jQuery Click - Stack Overflow

programmeradmin3浏览0评论

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();

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 ?

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();

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 ?

Share Improve this question edited Jun 10, 2012 at 15:47 TazGPL 3,7482 gold badges40 silver badges60 bronze badges asked Dec 18, 2011 at 10:48 Suave NtiSuave Nti 3,75713 gold badges56 silver badges78 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 10

This calls the anchorScr function when the anchor is clicked:

href="javascript:anchorScr()"

The function then attaches a click event handler to all a elements.

Remove the href and just have this:

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.

<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);
   });
});
发布评论

评论列表(0)

  1. 暂无评论