Anchor tag jQuery 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 ?

Answers


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

Need Your Help


About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.