通过单击HTML列表元素来调用javascript函数 [英] Call javascript function by clicking on HTML list element
问题描述
我是Web开发的新手,所以这个问题对其他人可能太明显了.我想制作一个菜单,当单击菜单项时,它需要使用一个参数(项目ID)来调用javascript函数.我想将菜单项显示为未编号列表.我不明白的是如何将相同的功能绑定到每个列表项,这将由服务器端php脚本生成.
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.
推荐答案
这有望使您朝着正确的方向前进.我正在做的就是将"onClick"事件侦听器绑定到所有li
元素,如果在其他地方使用它们,则可能需要更改绑定的内容.然后,当他们被单击时,他们调用函数myScript
,该函数将获取其ID并对其发出警报.
This will hopefully get you going in the right direction. All I'm doing is binding an "onClick" event listener to all li
elements, you might want to change what you bind to in case you use them elsewhere. Then when they are clicked they call the function myScript
which get's their ID and alerts it.
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
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);
}
这篇关于通过单击HTML列表元素来调用javascript函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!