简体   繁体   中英

Anchor tag onclick using unobtrusive javascript

<li id="Account_Tab" class="bgrad">
<a class="bganch" title="Accounts Tab" href="/xxx/xxx">Accounts</a>
</li>

there are few other <li> tags in the similar way , How can i create an onclick function for the anchor tag,

not like: <a onclick="function()"......> is there any other approach other than inline Javascript?

You can add the handler like so:

function anchorClicked(){
    console.log("clicked");
}

window.onload = function(){
    var anchors = document.getElementsByClassName('bganch');

    for(var i=0; i<anchors.length; i++){
        anchors[i].onclick = anchorClicked;
    }
};

The above adds the click event to elements with the bganch class.

Other options:

  • Give the anchor an ID and use document.getElementById('someid')
  • Get all anchors by the tag name using document.getElementsByTagName('a')

Try

window.onload = function(){
    var anchors = document.getElementsByClassName('bganch');

   var anchortitle= anchors.title;
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM