在Variable JS中使用onclick =“myFunction()”

时间:2017-11-11 09:15:06

标签: javascript jquery html

我有一个div {{1>}代表'显示/隐藏'onclick="myFunction()"

file.js 中的

我使用这样的格式:

id="myTable"

我想使用 function example () { var popup = '<div class="box">' + '<div onclick="myFunction()" id="button"></div>' + '<div id="myTable" class="myTable"></div>' + '</div>'; //box }; //End function example() /**** How to make myFunction () work? ****/ function myFunction() { var x = document.getElementById("myTable"); if (x.style.display === "none") { x.style.display = "block"; } else { x.style.display = "none"; } }; // End function myFunction() 显示和隐藏 div id myTable

如果在w3school上使用html格式,则可行。

但我使用 .js 文件格式。 除了使用变量

之外,我无法添加html代码

onclick="myFunction()"

W3Schools Toggle Show/Hide

1 个答案:

答案 0 :(得分:1)

<!DOCTYPE html>
<html>
<head>
    <title>Demo example</title>
</head>

<body>
<div id="hello"></div>
    <script>
    example();

    function example() {
        var popup = '<div class="box">HELLO World' +
            '<button id="button">Button</button>' +
            '<div id="myTable" class="myTable">Some Content Here</div>' +
            '</div>'; //box
            var el = document.getElementById('hello')
            el.innerHTML = popup;
           //alert(popup);
    }; //End function example()


    /**** How to make myFunction () work? ****/
    document.addEventListener('click', function(e) {
        console.log(e.target.id)
        if (e.target && e.target.id == 'button') { //do something
            myFunction()
        }
    })

    function myFunction() {
        var x = document.getElementById("myTable");
        if (x.style.display === "none") {
            x.style.display = "block";
        } else {
            x.style.display = "none";
        }
    };
    </script>
</body>

</html>

通过在此文档中使用此代码段来使用此代码段.addEventListener将侦听触发的所有点击,但仅当id与e.target.id中提供的指定ID匹配时才更新样式值你的js将在这里动态创建元素。在你的情况下onclick函数没有被触发,因为js没有链接在页面中动态创建的元素,并且通过事件委托我们可以解决这个问题。