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


As long as I can remember, I am doing the following:

  & Lt; Ul & gt; & Lt; Li & gt; & Lt; A href = "elsewhere" & gt; Some text & lt; / A & gt; & Lt; / Li & gt; & Lt; / Ul & gt;   

Since this is a list of links, and nothing else, I know that I can do this to simplify the structure:

  Lt; Ul & gt; & Lt; Li onclick = "window.location.href = 'somewhere'"> Some text & lt; / Li & gt; & Lt; / Ul & gt;   

I just lighten the HTML structure up to 50%. If I have 100 rows, then there will be 100 elements instead of 200. I

Of course, I should use event listeners instead of inline onclick , but I do not know how to Is ... how do I use event listeners to create a list of links (instead of inline onclick )? See inspiration for this.

If you ignore the use of jQuery, you can see basic jQuery tutorial binding click handler For such elements, you can set all together onclic

HTML:

  & lt; Ul & gt; & Lt; Li data-url = "http://www.google.com" & gt; Google & lt; / Li & gt; & Lt; Li data-url = "http://www.stackoverflow.com" & gt; Stack Overflow & lt; / Li & gt; & Lt; Li data-url = "http://www.superuser.com" & gt; Super User & lt; / Li & gt; & Lt; / Ul & gt;   

Javascript:

  $ ('li'). Click (function () {window.location.href = $ (this). Data ('Url');});    

Comments