简体   繁体   English

为什么这个JS链接需要2次点击才能触发?

[英]Why does this JS link require 2 clicks to trigger?

I'm working on a script which will go along with my already in place website. 我正在编写一个脚本,它将与我已经存在的网站一起使用。 Basically, when you click the Show/Hide button , it shows an overlay over the content div . 基本上,当您单击“ Show/Hide button ,它会在内容div显示叠加层。 Then there's an option to hide the entire div , both overlay, content, and container. 然后可以选择隐藏整个div ,包括叠加层,内容和容器。

Problem is, you have to click the hide link twice for it to hide all the divs. 问题是,你必须两次点击hide链接才能隐藏所有的div。

I have a working example here: 我在这里有一个工作的例子:

http://jsfiddle.net/charlescarver/8c3VZ/3/ http://jsfiddle.net/charlescarver/8c3VZ/3/

EDIT: I updated the jsFiddle with the correct version of the JS. 编辑:我用正确版本的JS更新了jsFiddle。 I had the incomplete one in there before. 我之前有一个不完整的那个。

Also, there's more to the script that allows cookies, I just didn't include it to reduce the amount of code. 此外,还有更多允许cookie的脚本,我只是没有包含它来减少代码量。

It's because the style.display attribute is undefined at first. 这是因为style.display属性最初是未定义的。 reversing the logic can fix this. 扭转逻辑可以解决这个问题。 Basically the reason why is because element.style.display directly reads the style attribute of the element and not a javascript attribute like in this element: 基本上是因为element.style.display直接读取元素的style属性而不是像这个元素中的javascript属性:

<div style="display:none;">blah</div>

because your element doesn't have the style attribute at first, it defaults to the else. 因为您的元素最初没有style属性,所以默认为else。 Switching the logic will default it to hiding it rather than showing it. 切换逻辑将默认它隐藏它而不是显示它。

http://jsfiddle.net/MpJDN/ http://jsfiddle.net/MpJDN/

function toggle_visibility(a) {
var b = document.getElementById(a);
if (b.style.display == "none") {
    b.style.display = "block";
}
else {
    b.style.display = "none";
}
}

Change your toggle_visibility() code to this to let jQuery's .toggle() and .css() do most of the work for you: 将你的toggle_visibility()代码改为此代码,让jQuery的.toggle().css()为你完成大部分工作:

<script>
    function toggle_visibility(a) {
        var item = $("#" + a);
        item.toggle();
        $.cookie("disp" + a, item.css("display"));
    }
</script>

The reason it wasn't working is that b.style.display in your original code only returns inline styles. 它不起作用的原因是原始代码中的b.style.display仅返回内联样式。 It does not return styles set by CSS rules. 它不返回CSS规则设置的样式。 If you really wanted to get that style, you could use jQuery's .css("display") method. 如果你真的想要获得那种风格,可以使用jQuery的.css("display")方法。 But, in this case, you can just use .toggle() and let that do all the work for you. 但是,在这种情况下,您可以使用.toggle()并让它为您完成所有工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM