Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/400.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript onclick触发器不';第一次点击就不能工作_Javascript_Onclick - Fatal编程技术网

Javascript onclick触发器不';第一次点击就不能工作

Javascript onclick触发器不';第一次点击就不能工作,javascript,onclick,Javascript,Onclick,我不明白为什么onclick函数在第一次单击时没有注册。具有onclick触发器的每个div必须第一次单击两次 所选功能(elmnt){ 如果(elmnt.style.backgroundColor==“透明”) elmnt.style.backgroundColor=“#990000” 其他的 elmnt.style.backgroundColor=“透明” } #容器{ 背景色:透明; 高度:100px; 宽度:100px; } 单击我该元素的背景色不是透明的,因此它总是转到else。将d

我不明白为什么onclick函数在第一次单击时没有注册。具有onclick触发器的每个div必须第一次单击两次

所选功能(elmnt){
如果(elmnt.style.backgroundColor==“透明”)
elmnt.style.backgroundColor=“#990000”
其他的
elmnt.style.backgroundColor=“透明”
}
#容器{
背景色:透明;
高度:100px;
宽度:100px;
}

单击我
该元素的背景色不是透明的,因此它总是转到else。将div更改为

<div id="container" onclick="selected(this)" style='background-color:transparent'>www</div>
www

我会让它工作的。css样式表不会物理地将样式附加到DOM元素。

这是因为您的元素样式是不透明的。只有元素的
computedStyle
是可用的。试试这个:

所选功能(elmnt){
如果(elmnt.style.backgroundColor==“透明”)
elmnt.style.backgroundColor=“#990000”
其他的
elmnt.style.backgroundColor=“透明”
}
#容器{
背景色:透明;
高度:100px;
宽度:100px;
}

单击我
以上两个答案完全一致,初始样式未设置

只是告诉你下次如何调试它 us console.log()单击F12获取开发人员工具,然后单击控制台选项卡

我喜欢简单的IF时使用简短的IF

 <script>
    function selected(elmnt) {
        console.log(elmnt.style.backgroundColor)
        var bG= elmnt.style.backgroundColor
        elmnt.style.backgroundColor = ( bG == '' || bG == "transparent") ? "#990000" : "transparent";
    }      
</script>

所选功能(elmnt){
console.log(elmnt.style.backgroundColor)
var bG=elmnt.style.backgroundColor
elmnt.style.backgroundColor=(bG=''| | bG==“透明”)?“#990000:“透明”;
}      

当您单击elmnt.style.backgroundColor时,尝试输出它。@j08691这将是
。啊!精彩的接球!:)这是正确的,但他不需要指定内联样式。这只会带来更多的维护。相反,更改
if
条件以查找空字符串,并将样式设置为空字符串以删除它。