英文:
React onClick doest work correctly on if conditional
问题
I have a problem with React.
I wrote a function:
function click(event) {
let element = event.currentTarget.querySelector(".infos__content");
if (element.style.display) {
alert("test")
element.style.display = "none";
}
else {
alert("test1")
element.style.display = "block";
}
}
and i called this function successfully in a DIV Container on the "onClick" attribute but it works for just one time, when i click on my div Container again, my if conditional always is true, does anyone know why?
I have google it already but cant find a solution for this
英文:
I have a problem with React.
I wrote a function:
function click(event) {
let element = event.currentTarget.querySelector(".infos__content");
if (element.style.display) {
alert("test")
element.style.display = "none";
}
else {
alert("test1")
element.style.display = "block";
}
}
and i called this function successfully in a DIV Container on the "onClick" attribute but it works for just one time, when i click on my div Container again, my if conditional always is true, does anyone know why?
I have google it already but cant find a solution for this
答案1
得分: 2
当您首次检查element
时,它将是''。这将计算为false。
element.style.display
''
然后当您分配'none'时,它将是'none'。
element.style.display='none'
'none'
element.style.display
'none'
'none'是一个真字符串值,因此表达式始终为true。要使您的评估为false,必须分配''或null
。
英文:
When you are first checking element
it will be ''. This will evaluate to false.
element.style.display
''
Then when you assign 'none', it will be 'none'.
element.style.display='none'
'none'
element.style.display
'none'
'none' is a true string value so the expression will always be true. To make your evaluation false you must assign '' or null
.
答案2
得分: 2
你还可以在你的函数内部使用if语句来检查元素的当前样式状态,然后相应地进行更改。
function click(event) {
let element = event.currentTarget.querySelector(".infos__content");
if (element.style.display === "block") {
alert("test");
element.style.display = "none";
}
else {
alert("test1");
element.style.display = "block";
}
}
英文:
You can also use If statement inside your function to check the current style state of your element and then change accordingly.
function click(event) {
let element = event.currentTarget.querySelector(".infos__content");
if (element.style.display === "block") {
alert("test")
element.style.display = "none";
}
else {
alert("test1")
element.style.display = "block";
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论