简体   繁体   中英

A single Event Listener for the various <a> elements

Is it possible in JavaScript to have only one single listener for all <a> elements?

<ul>
    <li><a href="#1">1</a></li>
    <li><a href="#2">2</a></li>
    <li><a href="#3">3</a></li>
    <li><a href="#4">4</a></li>
    <li><a href="#5">5</a></li>
</ul>

That listener should take a value (eg #4 ) to update some div.

I hope this piece of code helps you out, the listener attached on the ul tag is now catching all the click events on its children and parsing out their href values. You might want to use a jquery lib to further parse out the #hrefvalue.

  <ul>
<li><a href="#1">1</a></li>
<li><a href="#2">2</a></li>
<li><a href="#3">3</a></li>
<li><a href="#4">4</a></li>
<li><a href="#5">5</a></li>
</ul>
<script>
document.getElementsByTagName("ul")[0].addEventListener("click", function(e){
e.preventDefault();
alert(e.target.href);
});
</script>

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