简体   繁体   中英

<a> tag only working on double click and not single click

Hi I have a <a> tag that is working on double click but not on single click. I have a javascript function called on the tag.

Can someone help on same.

Below is the tag and the javascript function

function ShowPopup() { 
    $("#lnkAttachment").on("click", function () {
        $('#divProjectAttachment').modal('toggle');
    });
}

<a>href="javascript:void(0);" id="lnkAttachment" onclick="ShowPopup();">Click here to View Attachments!</a>

You're attaching event listener inside your ShowPopup function. Just update it to be like

function ShowPopup() { 
    $('#divProjectAttachment').modal('toggle');
}

And it will work fine.

Edit:

Why this happens?

Well, first of all, this works on 2nd click, not on double click .

Next,

You have attached onclick event handler in your <a></a> tag. Which triggers ShowPopup function. And inside your ShowPopup function you're re attaching click event listener to the same element. So first time when you click on your anchor tag, the ShowPopup will attach event listener to the #lnkAttachment . An important thing to note here is that that your ShowPopup function gets called on the first click. But it won't show you the popup because you're attaching the event listener to the element and that's it. Now the event listener is attached after the ShowPopup is called for the first time. Next time when you click on the lnkAttachment the event listener is already present so it wil lshow the popup. Additionally, it will re-attach the click event listener again (and everytime the ShowPopup is called - which is unnecessary).

You can either keep your code as this answer demonstrates

OR

You can decide to follow good programming ethos and separate event attachment (JavaScript) from your display markup (HTML) The way to do it is as follows.

Keep your anchor tag as

href="javascript:void(0);" id="lnkAttachment">Click here to View Attachments!

(Notice, no onclick event handler here)

and in your javascript you take care of event handling.

$(document).on('ready', function(){
    $("#lnkAttachment").on("click", function () {
        $('#divProjectAttachment').modal('toggle');
    });
}

When you are using jQuery, you can wire up the events without onclick in html.

<a>href="javascript:void(0);" id="lnkAttachment">Click here to View Attachments!</a>

You can remove the onclick in markup and write your jQuery script in DOM ready.

$(function(){
 $("#lnkAttachment").on("click", function () {
        $('#divProjectAttachment').modal('toggle');
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM