【问题标题】:How to call a function in JS without calling the function of Parent element如何在JS中调用函数而不调用Parent元素的函数
【发布时间】:2022-01-23 15:08:08
【问题描述】:

如何使按钮消失在下面的示例中起作用

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>title</title>
</head>
<body>
    <div id="div1" style="height: 100px; background-color: red;" onclick="parent()">
        <button onclick="child()">disapear</button>
    </div>
    
    <script>
        function parent(elem) {
            document.getElementById("div1").style.display = "block";
        }
        function child(elem) {
            document.getElementById("div1").style.display = "none";
        }
    </script>
</body>
</html>

当我点击按钮消失时,我只想调用它的函数——child()。不是我单击 div 时的 parent() 函数

【问题讨论】:

标签: javascript function dom-events parent-child


【解决方案1】:
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>title</title>
</head>
<body>
    <div id="div1" style="height: 100px; background-color: red;" onclick="parent(event)">
        <button onclick="child(event)">disapear</button>
    </div>
    
    <script>
        function parent(elem) {
            document.getElementById("div1").style.display = "block";
        }
        function child(elem) {
            elem.stopPropagation();
            document.getElementById("div1").style.display = "none";
        }
    </script>
</body>
</html>

【讨论】:

    猜你喜欢
    • 2022-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多