通过单击 HTML 列表元素调用 javascript 函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24665677/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 03:11:55  来源:igfitidea点击:

Call javascript function by clicking on HTML list element

javascripthtmlmenu

提问by Sergey777

I am new to web development so this question may be too obvious to others. I would like to make a menu, when menu item is clicked it needs to call javascript function with one argument, the item id. I would like to present menu items as a unnumbered list. What I do not understand is how to bind the same function to each list item, which will be generated by server-side php script.

我是网络开发的新手,所以这个问题对其他人来说可能太明显了。我想制作一个菜单,当单击菜单项时,它需要使用一个参数(即项 ID)调用 javascript 函数。我想将菜单项显示为未编号的列表。我不明白的是如何将相同的函数绑定到每个列表项,这些列表项将由服务器端 php 脚本生成。

回答by sharf

This will hopefully get you going in the right direction. All I'm doing is binding an "onClick" event listener to all lielements, you might want to change what you bind to in case you use them elsewhere. Then when they are clicked they call the function myScriptwhich get's their ID and alerts it.

这有望让您朝着正确的方向前进。我所做的只是将“onClick”事件侦听器绑定到所有li元素,您可能想要更改绑定到的内容,以防在其他地方使用它们。然后当他们被点击时,他们调用myScript获取他们的 ID 并提醒它的函数。

JSFiddle Demo

JSFiddle 演示

HTML

HTML

<ul>
    <li id="1">Link 1</li>
    <li id="2">Link 2</li>
    <li id="3">Link 3</li>
    <li id="4">Link 4</li>
    <li id="5">Link 5</li>
</ul

Javascript

Javascript

var li = document.getElementsByTagName("li");

for(var i = 0;i<li.length;i++){
    li[i].addEventListener("click", myScript);
}

function myScript(e){
    alert(e.target.attributes.id.value);       
}