# 避免直接在button上寫onclick="myFunction()
###### tags: `JavaScript`
很多教學使用button on click點擊啟動行為常常用
`<button onclick="myFunction()">Try it</button>`
這種寫法,但是<kbd>onclick="myFunction()</kbd>寫法有資安上問題,所以六角線上課時老師建議用 <kbd>document.getElementById</kbd>方式去啟動<kbd>Function()</kbd>
貼上[w3cshool範例](https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_onclick_dom)點進去有效果展示
[onclick Javascript行為參考](https://www.w3schools.com/jsref/event_onclick.asp)
```
<html>
<body>
<p>This example uses the HTML DOM to assign an "onclick" event to a p element.</p>
<p id="demo">Click me.</p>
<script>
document.getElementById("demo").onclick = function() {myFunction()};
function myFunction() {
document.getElementById("demo").innerHTML = "YOU CLICKED ME!";
}
</script>
</body>
</html>
```
使用<kbd>addEventListener</kbd>監聽觸發
[In JavaScript, using the addEventListener() method:](https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_onclick_addeventlistener)
```
<html>
<body>
<p>This example uses the addEventListener() method to attach a "click" event to a p element.</p>
<p id="demo">Click me.</p>
<script>
document.getElementById("demo").addEventListener("click", myFunction);
function myFunction() {
document.getElementById("demo").innerHTML = "YOU CLICKED ME!";
}
</script>
</body>
</html>
```