我想将事件监听器纯粹用Javascript附加到“ ul” html标记,以便当我单击任何“ li”时,警报将显示相应的“ li”的值:
<ul>
<li>A<li/>
<li>B<li/>
<li>C<li/>
</ul>
如果单击A它将提醒A,与B和C相同
答案 0 :(得分:1)
var list = document.querySelector("#list");
list.addEventListener("click", function(ev) {
if (ev.target !== list) console.log(ev.target.textContent);
// console is easier to test than alert(ev.target.textContent);
});
<ul id="list">
<li>A</li>
<li>B</li>
<li>C</li>
</ul>
答案 1 :(得分:0)
获取所有const { reject, flow, props, every, isEmpty } = _
const fn = reject(flow(props(['value', 'options']), every(isEmpty)))
const arr = [{"type": "price","value": {"min": 0,"max": 170}}, {"type": "name","value": {}}, {"type": "volume","options": [1,2]}]
const result = fn(arr)
console.log(result)
并在每个<script src='https://cdn.jsdelivr.net/g/lodash@4(lodash.min.js+lodash.fp.min.js)'></script>
上添加li nodes
click events
nodes
var lis = document.getElementById("div").getElementsByTagName("li")
for(var i=0;i<lis.length;i++){
lis[i].addEventListener('click', function(e){
alert(e.target.textContent);
})
}
// As if you want to have single click event on ul itself
document.getElementById("ul").addEventListener('click', function(e){
alert(e.target.textContent);
})
答案 2 :(得分:0)
您可以通过getElementById
选择ul并将其绑定到事件onclick
。检查
JSFiddle
答案 3 :(得分:-1)
document.querySelectorAll('li')
.forEach(item =>
item.addEventListener('click',
() => alert('Item clicked')
)
);
li {
cursor: pointer;
}
li:hover {
background: lightgrey;
}
<ul>
<li>Item 1</li>
<li>Item 2</li>
</ul>
您必须遍历列表中的所有<li/>
元素,并将eventListener附加到它们。
请参阅代码示例以了解其工作原理。