Onclick javascript函数仅在第二次单击时工作
Onclick javascript函数仅在第二次单击时工作,javascript,html,css,events,click,Javascript,Html,Css,Events,Click,function toggleDivFunction(){ var arrowElement=document.getElementById(“arrowRight”); var showElement=document.getElementById(“dropdownText”); arrowElement.onclick=函数(){ 如果(showElement.style.display==“无”){ showElement.style.display='block'; document.
function toggleDivFunction(){
var arrowElement=document.getElementById(“arrowRight”);
var showElement=document.getElementById(“dropdownText”);
arrowElement.onclick=函数(){
如果(showElement.style.display==“无”){
showElement.style.display='block';
document.getElementById(“arrowRight”).style=“变换:旋转(+90度)”;
}否则{
showElement.style.display='none';
document.getElementById(“arrowRight”).style=“变换:旋转(0deg)”;
}
}
}
TOP>
要显示的文本
您希望更早地分配事件处理程序:
window.onload=toggleDivFunction;
并删除onclick='toggleDivFunction()',这在当时是不必要的,也是老式的
您的代码在触发事件时分配侦听器(toggleDivFunction)。要触发侦听器(arrowElement.onclick),您需要再次单击另一个事件。您不需要在另一个
事件处理程序中绑定事件处理程序单击事件处理程序。您必须使用单个单击事件处理程序
show/hide
功能属于第二个click
事件处理程序,它在第一次click
之后绑定到span
DOM元素
function toggleDivFunction(){
var arrowElement=document.getElementById(“arrowRight”);
var showElement=document.getElementById(“dropdownText”);
如果(showElement.style.display==“无”)
{
showElement.style.display='block';
document.getElementById(“arrowRight”).style=“变换:旋转(+90度)”;
}
其他的
{
showElement.style.display='none';
document.getElementById(“arrowRight”).style=“变换:旋转(0deg)”;
}
}
TOP>
要显示的文本
删除箭头元素。onclick=function(){}
为什么?
您已经在onclick=toggleDivFunction()
中使用arrowRight
应用了该函数
首先执行toggleDivFunction()
,然后执行Dom
arrow元素。onclick
。使用onclick函数中的任何一个,而不是两个
function toggleDivFunction(){
var arrowElement=document.getElementById(“arrowRight”);
var showElement=document.getElementById(“dropdownText”);
如果(showElement.style.display==“无”){
showElement.style.display='block';
document.getElementById(“arrowRight”).style=“变换:旋转(+90度)”;
}否则{
showElement.style.display='none';
document.getElementById(“arrowRight”).style=“变换:旋转(0deg)”;
}
}
TOP>
待显示的文本
只是添加到已批准的答案中
检查showElement.style.display=''
此外,如果您使用默认值display='none'
,则要在第一次单击时切换到flex本身
例如:
..
if (showElement.style.display == 'none' || showElement.style.display == '') {
..
如果文本的样式是display='none'
只需删除以下内容:arrowElement.onclick=function(){}。您正在函数中添加一个事件侦听器,该函数应该捕获您的事件。没什么大不了的!