onclick事件在IE中触发两次,但在FF或Chrome中不触发

时间:2016-05-07 00:43:15

标签: javascript html internet-explorer

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

<?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';
        }
    </script>
</head>
<body>
    <div onclick="showHide('expandDiv')">
        <label id="outLabel" for="outText">Label</label>
        <span id="outText">This is an example of an</span>
    </div>
    <div id="expandDiv" style="display:block">
        <p>Expanded Div</p>
    </div>
</body>
</html>

2 个答案:

答案 0 :(得分:2)

这是一个稍短的版本。

<强> HTML

SELECT
    birth_date
    +
    cast(
        date_part('year', current_date)
        -
        date_part('year', birth_date)
        +
        CASE
            WHEN
                date_part('month', birth_date) <
                        date_part('month', current_date)
                OR (
                    date_part('month', birth_date) =
                            date_part('month', current_date)
                    AND
                    date_part('day', birth_date) <
                            date_part('day', current_date)
                )
            THEN 1
            ELSE 0
        END || ' year' as interval)
FROM person;

<强> JS

<div onclick="showHide('expandDiv', event)">

<强>演示

https://jsfiddle.net/1w4dxdkm/

答案 1 :(得分:1)

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

<?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';
            }
        }
    </script>
</head>
<body>
    <div onclick="showHide('expandDiv')">
        <label id="outLabel" for="outText">Label</label>
        <span id="outText">This is an example of an</span>
    </div>
    <div id="expandDiv" style="display:block">
        <p>Expanded Div</p>
    </div>
</body>
</html>