jQuery data function usage with keywords

92 views Asked by At

My HTML:

 <a id="link" class="linkRedirect" data-href="">Download Link</a>

I am getting incorrect value for $("#link").data("href") when clicked multiple times.

Click Handler:

 $(document).on("click", "#link", function (e) {
            var url = $("#link").data("href");
            //check validation
            if(true) location.href = url;
 });

The file in the url will be downloaded only if the session is valid.

3

There are 3 answers

0
Sayed On

You could rather use it like this:

<a id="link" class="linkRedirect" rel="somelink">Download Link</a>

then ins your jquery, use this:

 $(document).on("click", "#link", function (e) {
            var url = $("#link").attr("rel");
            //check validation
            if(url)//apply whatever check you want
             location.href = url;
 });
1
enguerranws On

Your jQuery code is really weird. Anyway check with that:

$('#link').click(function(){
  var url = $("#link").attr("data-href"); 
  if(url){
    window.location = url;
  }
});

I didn't test it but that would work better than your code :)

0
Joseph On

Got the problem. When I renamed attribute data-href to data-url, the issue was solved.

$("#link").data("href")

The value obtained was that of href attribute and not data-href.