2017-11-11 41 views
0

我有一个div它有onclick="myFunction()"'显示/隐藏'id="myTable"在变量JS中使用onclick =“myFunction()”JS

file.js我使用的格式是这样的:

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() 

我想显示和使用onclick="myFunction()"隐藏 DIV ID myTable

如果使用上w3school HTML格式,这个工程。

但是我用的是的.js文件格式。 我不能添加其他HTML代码比使用可变

var ex = '<htmlcode></htmlcode>';

W3Schools Toggle Show/Hide

+0

附加链接的工作原理是什么? – Sajeetharan

+0

请用[MCVE]证明问题更新您的问题,最好是一个** **可运行一个使用堆栈片段(在'[<>]'工具栏按钮;在这里是如何做到这一个](https://开头元。 stackoverflow.com/questions/358992/ive-been-told-to-do-a-runnable-example-with-stack-snippets-how-do-i-do-tha)。如果没有更多的信息,我们真的不能帮助你 –

+0

一个注意:您与单击处理div有什么也没有,所以,除非你使用CSS样式它,这将是0像素高,这使得它比较硬点击另一个问题是,'onxyz' -attribute式的事件处理程序只能拨打*全球*的功能(这是因为以下原因而不能使用它们),那么你的'myFunction'必须是全球性的。是吗? –

回答

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> 

使用通过利用这个片段在此document.addEventListener此代码段会听所有的点击只有当id与e.target.id中提供的指定ID相匹配时,才会触发它,但更新样式值,通过这种方法,您的js将在这里动态创建元素。在您的情况下,onclick函数不会被触发,因为js没有链接元素动态创建在页面中,通过事件授权,我们可以解决这个问题。

+0

非常感谢myHero()。 – Ananda