2013-09-21 158 views
2

我想獲得a標記的hrefhash的值。當我做通過jQuery獲取href值

$(document.body).on('click',"a",function(event){ 
    console.log($(this)); 
}); 

我看到一個物體的東西,如

[a.internalLink, context: a.internalLink, jquery: "1.10.2", constructor: function, init: function, selector: ""…] 
    0: a.internalLink 
     accessKey: "" 
     attributes: NamedNodeMap 
     ... 
     hash: "#abc.1.2" 
     ... 
     href: "http://www.example.com/page.html#abc.1.2 
     ... 

但是,當我試圖通過console.log($(this).href)得到的價值,它只是不工作(打印出「不確定」)。我怎麼才能得到它?

+2

只是'this.href'或'$(this).attr('href')' – kalley

回答

3

如果你想引用一個元素的特定屬性,你可以使用jQuery的attr功能:

$(document.body).on('click',"a",function(event){ 
    console.log($(this).attr("href")); 
}); 
1
$('body').on('click', 'a', function() { 
    console.log($(this).attr('href')); 
}); 
1
$(document.body).on('click',"a",function(event){ 
    console.log($(this).attr('href')); 
    event.preventDefault(); 
}); 
0

根據你的代碼點擊「」標籤會給名單您的頁面中所有錨定標記對象的排列順序爲$(this)。而且每個對象有jQuery的特定屬性(如包裹在jQuery的)類似的href,哈希等

所以,如果你只有一個錨標記,那麼你可以使用$(this)[0].href

但更具體的解決方案使用起來會$(this).attr("href")

0

你可以得到兩個:全HREF或者只是使用此代碼的哈希:

$("body").on("click","a",function() { 
    var href = $(this).attr("href") 
    var hash = href.replace(/^.*?#/,''); 
    console.log(href + " - " + hash); 
}); 

你可以看到一個demo on JSFiddle