Home > Mobile >  How to handle jQuery events through link tags
How to handle jQuery events through link tags

Time:08-17

I have a link on which I have attached an attribute setnumber.

 <a  href="page1.html" data-setnumber="100">Link to page 1</a>

I want to get this attribute as soon as the user clicks on the link, then I will use this attribute through JQuery to save some information into the database.

$(document).on('click','.link-container',function(){ 
    var el = $(".link-container").attr("data-setenumber");
    alert(el);
});

After that or at the same time, I would let the user go to the requested page (page1.html). But I never get into the JQuery file. I directly go to page1.html.
Is there a better way to do this with a link? The goal is to fill a mySQL table after the user clicks on the link, then bring the user to page1.html.

CodePudding user response:

$(document).on('click','.link-container', function(event){ 
    event.preventDefault();
    var el = $(".link-container").data("setnumber");
    alert(el);
});

CodePudding user response:

Do not use href to go to the requested page page1.html. First get value of data-setenumber attribute and then redirect to page1.html.

<a  href="javascript:void(0);" data-setnumber="100">Link to page 1</a>
$(document).on('click','.link-container',function(){ 
    var el = $(".link-container").attr("data-setenumber");
    alert(el);
    window.location.href = "http://localhost/page1.html";
});
  • Related