如何使用三元运算符重写此代码?
How can I rewrite this code using a ternary operator?
以下是我编写的代码,用于在单击时将网格颜色更改为靛蓝,然后在第二次单击时删除该颜色。但是,我不知道如何使用三元运算符重写 if-else 语句。
const grid1=document.querySelector(".cell01")
grid1.addEventListener("click", (e)=>{
console.log(e);
if (grid1.style.backgroundColor) {
grid1.style.backgroundColor = "";
} else {
grid1.style.backgroundColor = "indigo";
}
})
提前感谢您的帮助(:
更新
感谢您的回答!但现在我又多了一个疑问——我想尝试不同的方法来重写相同的代码,并想出了这个:
grid1.style.backgroundColor=(grid1.style.backgroundColor!=true) ? "indigo" : "";
表达式(grid1.style.backgroundColor==false)
完全符合我的要求,但前者不是。有什么原因吗?
您可以通过从对象中获取 属性 进行赋值。
backgroundColor = { indigo: '', '': 'indigo' }[backgroundColor];
直接翻译成三元:
grid1.style.backgroundColor = grid1.style.backgroundColor ? "" : "indigo";
grid1.style.backgroundColor = grid1.style.backgroundColor ? '' : 'indigo'
你可以试试这个:
grid1.style.backgroundColor = grid1.style.backgroundColor ? "" : "indigo";
查看下面的参考资料以了解有关三元运算符的更多信息
https://www.freecodecamp.org/news/ternary-operator-javascript-if-statement-tutorial/
通过使用三元运算符,您可以根据控件名称简单地更改代码。
var button = document.querySelector("button");
button.addEventListener("click", function() {
const curColour = document.body.style.backgroundColor;
document.body.style.backgroundColor = curColour === 'red' ? 'blue' : 'red';
});
以下是我编写的代码,用于在单击时将网格颜色更改为靛蓝,然后在第二次单击时删除该颜色。但是,我不知道如何使用三元运算符重写 if-else 语句。
const grid1=document.querySelector(".cell01")
grid1.addEventListener("click", (e)=>{
console.log(e);
if (grid1.style.backgroundColor) {
grid1.style.backgroundColor = "";
} else {
grid1.style.backgroundColor = "indigo";
}
})
提前感谢您的帮助(:
更新
感谢您的回答!但现在我又多了一个疑问——我想尝试不同的方法来重写相同的代码,并想出了这个:
grid1.style.backgroundColor=(grid1.style.backgroundColor!=true) ? "indigo" : "";
表达式(grid1.style.backgroundColor==false)
完全符合我的要求,但前者不是。有什么原因吗?
您可以通过从对象中获取 属性 进行赋值。
backgroundColor = { indigo: '', '': 'indigo' }[backgroundColor];
直接翻译成三元:
grid1.style.backgroundColor = grid1.style.backgroundColor ? "" : "indigo";
grid1.style.backgroundColor = grid1.style.backgroundColor ? '' : 'indigo'
你可以试试这个:
grid1.style.backgroundColor = grid1.style.backgroundColor ? "" : "indigo";
查看下面的参考资料以了解有关三元运算符的更多信息 https://www.freecodecamp.org/news/ternary-operator-javascript-if-statement-tutorial/
通过使用三元运算符,您可以根据控件名称简单地更改代码。
var button = document.querySelector("button");
button.addEventListener("click", function() {
const curColour = document.body.style.backgroundColor;
document.body.style.backgroundColor = curColour === 'red' ? 'blue' : 'red';
});