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(){}。您正在函数中添加一个事件侦听器,该函数应该捕获您的事件。没什么大不了的!