javascript 列表项数组上的 Onclick 事件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17265167/
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
Onclick event on an array of list items
提问by akinuri
I have a list and I want to create a function that will bold the clicked list item. So far I managed to create a function and assign it to list items. Onclick, it bolds, but just one item. I don't know how to set it for each item.
我有一个列表,我想创建一个函数来加粗单击的列表项。到目前为止,我设法创建了一个函数并将其分配给列表项。Onclick,它加粗,但只有一项。我不知道如何为每个项目设置它。
I could have used id to bold the items but there will be a lot of items in the list. I can't deal with each one of them.
我可以使用 id 来加粗项目,但列表中会有很多项目。我无法处理它们中的每一个。
html
html
<ul>
<li>apple</li>
<li>orange</li>
<li>banana</li>
</ul>
javascript
javascript
var list = document.getElementsByTagName("li");
function markSelection() {
if(list[0].style.fontWeight !== "bold") {
list[0].style.fontWeight = "bold";
} else {
list[0].style.fontWeight = "normal";
}
}
for (i = 0, len = list.length; i < len; i++){
list[i].onclick = markSelection;
}
It bolds only list[0]. How can I set it to bold the clicked list item?
它仅加粗列表 [0]。如何将其设置为加粗单击的列表项?
回答by gdoron is supporting Monica
function markSelection() {
if(this.style.fontWeight !== "bold") {
this.style.fontWeight = "bold";
} else {
this.style.fontWeight = "normal";
}
}
for (i = 0, len = list.length; i < len; i++){
list[i].onclick = markSelection;
}
回答by Achrome
回答by AntouanK
Why not using a class and toggle it whenever you want ( for example adding it on click, and let css handle the style )
为什么不使用类并在需要时切换它(例如在单击时添加它,并让 css 处理样式)
http://jsfiddle.net/blackjim/by9bP/2/
http://jsfiddle.net/blackjim/by9bP/2/
var list = document.getElementsByTagName("li");
function markSelection() {
if(this.className.indexOf('boldFruit')===-1){
this.className += " boldFruit";
}
}
for (i = 0, len = list.length; i < len; i++){
list[i].onclick = markSelection;
}
CSS
CSS
li {
font-size: 20px;
}
li.boldFruit {
font-weight: bold;
}