attr
函数:$(document.body).on('click',"a",function(event){
console.log( $(this).attr("href") );
});
$('body').on('click', 'a', function () {
console.log($(this).attr('href'));
});
$(document.body).on('click',"a",function(event){
console.log($(this).attr('href'));
event.preventDefault();
});
$( "a" )[0].href
或者 $( "a" ).attr( "href" )
。
你可以使用这段代码获取完整的 href 或者只获取 hash:
$("body").on("click","a",function() {
var href = $(this).attr("href")
var hash = href.replace(/^.*?#/,'');
console.log(href + " - " + hash);
});
你可以在JSFiddle上看到一个演示。
$(this)
提供页面中所有锚点对象的列表。每个对象都有特定于jQuery的属性(如用jQuery包装的this)例如href、hash等。$(this)[0].href
但更具体的解决方案是使用$(this).attr("href")
this.href
或$(this).attr('href')
。 - kalley