クリックした要素を参照する必要があります。1 つの方法はthis
、timeJV が提案したように渡すことです。
しかし、別のスクリプト ブロックからイベント ハンドラーを設定し、現在の要素を参照するだけです。次の 2 つのソリューションの両方で、追加のインライン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() */