how to get jquery anchor href value

2019-04-19 16:08发布

问题:

jQuery:

$(document).ready(function() {
    $("a.change_status").click(function(){
       var status_id = $("a").val();
       alert(status_id); 
       return false;
    });
});

HTML:

<a href="?status=5" class="change_status">Aminul</a><br/>
<a href="?status=25" class="change_status">Arif</a><br/>
<a href="?status=15" class="change_status">Sharif</a><br/>

I need status_id and for some reason my anchor tag is dynamic. I can't use id or make class name dynamic. I think, I need to use $this to get my value.

回答1:

This one is simple :

     $(document).ready(function() {
         $("a.change_status").click(function(){
           var status_id = $(this).attr('href').split('=');
           alert(status_id[1]); 
           return false;
        });
    });

http://jsfiddle.net/NmzRV/



回答2:

var status_id= $(this).attr("href").match(/status=([0-9]+)/)[1];


回答3:

You have two separate issues here... first you need to find the actual clicked link using this and then find the value of that href attribute.

$(document).ready(function() {
    $("a.change_status").click(function() {
        var status_id = parseURL($(this).attr("href"));
        alert(status_id);
        return false;
    });
});

Also, because javascript doesn't have a way to pull URL parameters, you must write a function (in the example parseURL) in which to find the value of the variable "status":

function parseURL(theLink) {
    return decodeURI((RegExp('status=' + '(.+?)(&|$)').exec(theLink) || [, null])[1]);
}

See the following jsfiddle:

http://jsfiddle.net/ZKMwU/



回答4:

$('a').attr('href');

should do the trick



回答5:

$(document).ready(function() {
        $("a.change_status").click(function(){
           var status_id = $(this).attr("href");
           alert(status_id); return false;
        });
    });


回答6:

You can do this like :

$(document).ready(function() { 
  $("a.change_status").click(function() { 
      var status_id = $(this).attr("href"); 
      alert(status_id);
      return false;
  }); 
});


回答7:

$("a.change_status").click(function(){ 
     var status_id = $(this).attr('href'); 
     alert(status_id); 
});


标签: jquery anchor