我有这个HTML:
<button onclick="hello()">Click Me</button>
<p class="myelement">Hello world 1</p>
<p class="myelement">Hello world 2</p>
这是我的JS:
function hello(){
alert('hello!');
var ele = document.getElementsByClassName("myelement");
ele.style.setProperty("text-decoration", "line-through");
}
按下按钮后,如何将文字更改为删除线?
注意:我正在寻找vanilla JS方法。不是jQuery方式。
答案 0 :(得分:5)
使用JSFiddle
https://jsfiddle.net/jqa7xjmf/2/
for (var i in ele)
ele[i].style.textDecoration='line-through'
ele是一个数组,所以你应该自己更改每个元素
function hello(){
var ele = document.getElementsByClassName("myelement");
for (var i in ele)
ele[i].style.textDecoration='line-through'
}
&#13;
<button onclick="hello()">Click Me</button>
<p class="myelement">Hello world 1</p>
<p class="myelement">Hello world 2</p>
&#13;
答案 1 :(得分:3)
由于document.getElementsByClassName
返回具有所有给定类名的所有子元素的类数组对象。你需要使用for
循环迭代它返回的元素。
var ele = document.getElementsByClassName("myelement");
for(var i=0;i<ele.length;i++){
ele[i].style.setProperty("text-decoration", "line-through");
}
答案 2 :(得分:1)
<script>
function hello()
{
var ele = document.getElementsByClassName("myelement");
for (i = 0; i < ele.length; i++) {
ele[i].style.textDecoration = "line-through";
}
}
</script>
<button onclick="hello()">Click Me</button>
<p class="myelement">Hello world 1</p>
<p class="myelement">Hello world 2</p>