关于 javascript:onclick 事件在 IE 中触发两次但不在 FF 或 Chrome 中触发

onclick event triggers twice in IE but not in FF or Chrome

我在package标签和跨度的 div 上有一个 onclick 事件。在IE中,如果标签被点击,则事件被触发两次,如果span被点击,则事件被触发一次。这在其他浏览器中不会发生。这是一个示例代码:

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
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC"-//W3C//DTD XHTML 1.0 Transitional//EN"
 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
    <script type="application/javascript">
        function showHide(id) {
        var node = document.getElementById(id);
        if (node.style.display !="none")
            node.style.display = 'none';
        else
            node.style.display = 'block';
        }
   
</head>
<body>
   
        <label id="outLabel" for="outText">Label</label>
        <span id="outText">This is an example of an</span>
   
   
        <p>Expanded Div</p>
   
</body>
</html>


这是一个略短的版本。

HTML

1
 

JS

1
2
3
4
5
6
7
function showHide(id, event) {
  var node         = document.getElementById(id),
      curr_display = node.style.display;

  node.style.display = curr_display ==="block" ?"none" :"block";  
  event.preventDefault();
}

演示

https://jsfiddle.net/1w4dxdkm/


添加 event.preventDefault(); 在 IE 和 Chrome 中按预期工作

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
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC"-//W3C//DTD XHTML 1.0 Transitional//EN"
 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
    <script type="application/javascript">
        function showHide(id) {
        event.preventDefault();
        var node = document.getElementById(id);
        if (node.style.display !="none"){
            node.style.display = 'none';
        }else{
            node.style.display = 'block';
            }
        }
   
</head>
<body>
   
        <label id="outLabel" for="outText">Label</label>
        <span id="outText">This is an example of an</span>
   
   
        <p>Expanded Div</p>
   
</body>
</html>