2012-03-12 94 views
0

我需要從href按鈕獲取值。在這裏,我剛剛開發了一個顯示所有href值的代碼。其實我需要從點擊的位置獲得價值。Jquery獲取href值

這裏是我的代碼

$(document).ready(function() { 
    $("a.me").click(function(){ 
    var number = $('a').text(); 

    alert(number); 

    }); 
}); 
+1

試$(本),而不是$(一) – 2012-03-12 12:46:16

回答

1

在jQuery中可以使用$(this)來引用被點擊的元素(或以其他方式使用)

像這樣:

$("a.me").click(function(){ 
    var number = $(this).text(); 
    alert(number); 
}); 
5

你應該做

$(document).ready(function() { 
    $("a.me").click(function(){ 
    //It's not clear if you want the href attribute or the text() of the <a> 
    //this gives you the href. if you need the text $(this).text(); 
    var number = this.href; 
    alert(number); 

    }); 
}); 
2
$("a.me").click(function(){ 
    var number = $(this).attr('href'); 
    alert(number); 
}); 
+0

這個答案的效果最好。即#anchor而不是website.com/page.html#anchor或點擊文本的值。 – spitfire 2014-11-18 19:16:00

0
var number = $(this).attr('href'); 
+0

不需要使用$(this).attr('href')',你正在做兩個額外的jQuery調用 – 2012-03-12 12:48:51

0
$(document).ready(function() { 
    $("a.me").click(function(){ 
     var target=$(this).attr("href"); 
     alert(target); 
    }); 
}); 
0

其中一個答案上面會工作,或者如果你只需要錨,你可以使用

... 
$("a.me").click(function(e){ 
    var number = $(e.target).text(); 
    alert(number); 
});