关于javascript:.toggle()有时需要双击才能工作

.toggle() sometimes taking double click before working

我有一个简单的应用程序,我想使用jQuery的.toggle效果在显示和隐藏字段集中的元素之间切换。问题是,有时我不得不双击启用切换的按钮才能使其正常工作。

有什么想法吗?

HTML:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<!DOCTYPE html>
<html>
<head>
    <script src="jquery-2.1.1.min.js">
    <script src="test.js">
</head>
<body>
   
    Left
   
    Main
   
       
        <form><fieldset><legend><button id="buttonShowFields">Add Info</button></legend>
       
            ID: <input type="text">
            Serial Number: <input type="text">
            Location: <select id="inputLocation">
            <option>Location1</option>
            <option>Location2</option></select>
            Status: <select id="inputStatus">
            <option>Complete</option>
            <option>In Process</option></select>
       
        </fieldset></form>
   
   
</body>
</html>

...和javascript(上面html中的test.js引用):

1
2
3
4
5
6
7
8
$(document).ready(function(){
// Show options to add workorder
    // $("#WOAddFields").hide();
    $("#buttonShowFields").click(function(){
    $("#InfoAddFields").toggle();
    });

});


当使用普通的javaScript来切换具有以下功能的元素时,我遇到了同样的问题:

1
2
3
4
5
function toggle(element){
  if (element.style.display !=="none")
    element.style.display ="none";
  else element.style.display ="block";
}

我注意到,当我向要切换的元素的CSS添加display:none时,我需要双击以首先显示该元素。要解决此问题,我必须在HTML元素标签中明确添加style =" display:none"。


单击按钮时使用event.preventDefault()防止提交

http://jsfiddle.net/3NPPP/

1
2
3
4
5
6
7
$(document).ready(function(){
    $("#buttonShowFields").click(function(e){
       e.preventDefault();
       $("#InfoAddFields").toggle();
    });

});

请更改事件方法以进行绑定,而不是单击。

1
2
3
$("#buttonShowFields").bind('click',function(){
    $("#InfoAddFields").toggle();
});

而不是这个...

1
    <button id="buttonShowFields">Add Info</button>

使用此...

1
    <input type="button" id="buttonShowFields" value="Add Info" />