Javascript onclick 需要单击两次才能运行函数

发布于 2024-11-14 02:15:15 字数 1431 浏览 9 评论 0原文

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

木森分化 2024-11-21 02:15:16

问题出在您的点击处理程序 boxBegin 内部 - 单击事件在第一次点击时被接收并正确传递给您的方法,但在 boxBegin 内部,您正在根据以下值切换行为box.style.display - 在 IE9 中,这最初是“”,它会触发您的关闭代码而不是您想要的打开代码。

更改框开始为:

function boxBegin() {
    var box = document.getElementById('boxBegin');
    if (!box.style.display || box.style.display == "none") {
        box.style.display = "block";
    }
    else {
        box.style.display = "none";
    }
}

The problem is inside your click handler boxBegin - the click event is received and passed to your method correctly on the first click, but inside boxBegin you are switching behaviour on the value of box.style.display - in IE9 this is initially "", which triggers your close code rather than the open code you want.

Change boxBegin to:

function boxBegin() {
    var box = document.getElementById('boxBegin');
    if (!box.style.display || box.style.display == "none") {
        box.style.display = "block";
    }
    else {
        box.style.display = "none";
    }
}
我三岁 2024-11-21 02:15:16

当我遇到同样的问题时,我用谷歌搜索了这个。

我正在检查 window.location.hash 是否为某个值,然后相应地设置菜单选项卡的样式。

对我来说,解决方案就像运行 10 毫秒的延迟函数一样简单,然后运行我的主要函数。

对我来说,问题来自于一个脚本,它在更改发生的同时恰好检查更改,不是之前,不是之后,而是同时。这使得我必须双击它才能再次更改,并且该函数才能第二次注意到更改。

请记住,当事情似乎没有记录更改时,即使运行 5 毫秒的延迟脚本也总是更容易。这一次又一次地帮助了我

I googled this when I came upon the same problem.

I was checking for if window.location.hash was a certain value, then styling my menu tabs accordingly.

For me, the solution was as simple as running a 10 millisecond delay function, that then ran my main functions.

The problem for me came from a script that checked for a change at the exact same time as the change was made, not before, not after, but at the same time. This made me have to double click for it to change again, and for the function to notice the change a second time around.

Remember, it's always easier to run even a 5 millisecond delay script when things don't seem to register changes. This has helped me time and time again

三五鸿雁 2024-11-21 02:15:16

据我所知, onclick 注册单击?

如果 onclick 需要双击,则可能是浏览器特定的问题。

同样来自 MDC 文档

当点击事件发生时
用户单击一个元素。点击声
事件将在鼠标按下后发生
和 mouseup 事件。

另外:简单的测试用例@ JS Fiddle

As far as I know, onclick registers single click?

If onclick requires a double click it might be a browser specific issue.

Also from the MDC docs:

The click event is raised when the
user clicks on an element. The click
event will occur after the mousedown
and mouseup events.

Also: simple test case @ JS Fiddle

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文