gpt4 book ai didi

javascript - 根据条件结果应用属性

转载 作者:行者123 更新时间:2023-11-30 19:14:36 25 4
gpt4 key购买 nike

var condition = 1 == 1;
if (condition) {
document.getElementById('result').classList.add('success');
} else {
document.getElementById('result').classList.remove('success');
}
.success:after {
background: green;
color: white;
content: "Success";
}

span:after {
background: red;
color: white;
content: "Failed";
}
<span id="result" data-result=""></span>

我想根据上面的条件应用这样的东西来操作 .add.remove 的属性

document.getElementById('result').classList.(condition ? add('success') : remove('success'));

可以吗?

最佳答案

你可以拿property accessorconditional (ternary) operator ?:并使用所需的字符串调用该函数。

var condition = 1 == 1;

document
.getElementById('result')
.classList[condition ? 'add' : 'remove']('success');
.success:after { background: green; color: white; content: "Success"; }
span:after { background: red; color: white; content: "Failed"; }
<span id="result" data-result=""></span>

关于javascript - 根据条件结果应用属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58148359/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com