javascript - javascript更改父元素样式
问题描述
我有一个工作代码为 html 中的当前元素添加下划线,当我再次点击时我想清理它
var button = document.getElementsByTagName("button");
for (var i = 0; i < button.length; i++) {
button[i].addEventListener('click', function() {
this.parentElement.getElementsByTagName('span')[0].style = "text-decoration:line-through";
if (this.parentElement.style == 'text-decoration:line-through') {
this.parentElement.getElementsByTagName('span')[0].style = "text-decoration:none"
}
});
}
<!doctype html>
<html>
<body>
<div id="tasks">
<div>
<button>Finish</button>
<span>Finish web tasks</span>
</div>
<div>
<button>Finish</button>
<span>Go to gym</span>
</div>
<div>
<button>Finish</button>
<span>Clean home</span>
</div>
<div>
<button>Finish</button>
<span>Start project</span>
</div>
<div>
<button>Finish</button>
<span>Prepare to calculus</span>
</div>
</div>
</body>
</html>
解决方案
只需检查是否 textDecoration == 'line-through',如果没有将其设置为 'line-through',如果是,将其设置为 'none'
<!doctype html>
<html>
<head>
</head>
<body>
<div id="tasks">
<div>
<button>Finish</button>
<span>Finish web tasks</span>
</div>
<div>
<button>Finish</button>
<span>Go to gym</span>
</div>
<div>
<button>Finish</button>
<span>Clean home</span>
</div>
<div>
<button>Finish</button>
<span>Start project</span>
</div>
<div>
<button>Finish</button>
<span>Prepare to calculus</span>
</div>
</div>
<script type="text/javascript">
var button = document.getElementsByTagName("button");
for(var i = 0; i<button.length;i++){
button[i].addEventListener('click', function() {
if(this.parentElement.style.textDecoration == 'line-through'){
this.parentElement.style.textDecoration = 'none';
} else {
this.parentElement.style.textDecoration = "line-through";
}
});
}
</script>
</body>
</html>
推荐阅读
- android - 以编程方式设置主屏幕壁纸(更改主屏幕和锁定屏幕)
- php - PHP - 将包模型扩展为您自己的
- r - 导入 -100 作为 NA
- haskell - 无法将预期类型“a -> Int”与实际类型“IOArrow String Int”匹配
- c# - 如何打破绑定以便删除资产
- oauth-2.0 - 通过 OAUTH 2 获取令牌时查看 Postman 中的一系列请求
- c# - asp.net 核心在视图中显示表格,每行旁边都有按钮。单击按钮后对数据库进行更改
- security - Travis CI 中的文件加密如何工作?
- powershell - Powershell获取给定路径内的扩展文件
- javascript - 反应打印运动属性内的值