开发者

List of Links: Using Event Listeners to Keep My HTML Structure As Simple As Possible

开发者 https://www.devze.com 2023-02-17 01:47 出处:网络
I\'ve been doing the following for as long as I can remember: <ul> <li><a href=\"somewhere\">Some text</a></li>

I've been doing the following for as long as I can remember:

<ul>
  <li><a href="somewhere">Some text</a></li>
</ul>

Since it's just a list of links, nothing else, I know I can do this to simplify the structure:

<ul>
  <li onclick="window.location.href='somewhere'">Some text</li>
</ul>

I've just lightened the HTML structure by 50%. If I have 100 rows, I’d have 100 elements instead of 200.

Of course, I should use event listeners instead on inline onclick, but I don't know how... How do I use event listeners (instead of inline onclick) to create a list of links? See开发者_开发知识库 here for the motivation for this.


If you do not mind using jQuery, you could have a look at basic jQuery tutorials of binding click handlers to elements. This way, you can set an onclick to all <li> at once:

http://jsfiddle.net/7zba5/1/

HTML:

<ul>
    <li data-url="http://www.google.com">Google</li>
    <li data-url="http://www.stackoverflow.com">Stack Overflow</li>
    <li data-url="http://www.superuser.com">Super User</li>
</ul>

JavaScript:

$('li').click(function() {
    window.location.href = $(this).data('url');
});
0

精彩评论

暂无评论...
验证码 换一张
取 消