如何使用javascript从类中的链接获取标题属性

How to get title attribute from link within a class with javascript

本文关键字:链接 获取 标题 属性 何使用 javascript      更新时间:2023-09-26

我正在尝试从类内的链接中提取标题属性,但遇到了一些麻烦:

<div class="menu">
<a href="#" title="4242" onclick="cselect()">United States</a>
<a href="#" title="4243" onclick="cselect()">Canada</a>
</div>

这是我尝试过的:

function cselect(){
    var countryID = $(this).attr("title");
    location.href = location.href.split("#")[0] + "#" +countryID;
    location.reload();
}

谢谢!

传入this传递给内联处理程序:

function cselect(obj){
    var countryID = $(obj).attr("title");
    console.log(countryID);
}
<a href="#" title="4242" onclick="cselect(this)">United States</a>
<a href="#" title="4243" onclick="cselect(this)">Canada</a>

演示:http://jsfiddle.net/yDW3T/

您必须引用单击的元素。一种方法是通过this,正如tymeJV所建议的那样。

但是我会从单独的脚本块设置事件处理程序,只引用当前元素。对于以下两个解决方案,不需要额外的内联onclick属性。

/* using jQuery */
jQuery( '.menu a' ).on( 'click', function( event ) {
    event.preventDefault();
    var countryID = jQuery( this ).attr( 'title' ); // <-- !!!
    location.href = location.href.split( '#' )[0] + '#' + countryID;
    location.reload();
} );

/* using plain JS */
var countryAnchors = document.querySelectorAll( '.menu a' );
for( var anchor in countryAnchors ) {
    anchor.addEventListener( 'click', function( event ) {
        event.preventDefault();
        var countryID = this.getAttribute( 'title' ); // <-- !!!
        location.href = location.href.split( '#' )[0] + '#' + countryID;
        location.reload();
    }, false );
}
/* todo: cross-browser test for compatibility on querySelectorAll() and addEventListener() */

它就像这样简单:

function cselect(){
    var countryID = $(this).attr("title");
    window.location.hash = countryID
    location.reload();
}