问题描述
<button id=trainingbutton document.getElementById("trainingbutton").addEventListener("click",}); ></button>
function(){
trainingbuttonclicked=()=>document.getElementById("trainingbtn").innerHTML = "Hello World";
JavaScript的新手,它正试图挂钩一个按钮以显示警报。上面是我的HTML,下面是我的app.js。我想尝试不使用简单的onclick事件处理程序来挂接事件。我首选的方法是事件处理程序或内部HTML方法。任何建议表示赞赏。我知道这很简单,但也许我凝视了太久了,因为我看不到答案
解决方法
您需要脚本标签才能插入事件监听器,就像这样
<script>
const button = document.querySelector('#trainingButton"); // # id's and . for selecting a
class in the dom (document object model)
button.addEventListener('click',function(event) {
const string = 'some string';
alert(string);
});
</script>
Your Button id should only contain a string like trainingButton so that it becomes <button id="trainingButton">
> the script tag should be placed in the bottom of your body tag,in order for the DOM to load properly before any javascript runs
for more info
https://www.w3schools.com/jsref/met_element_addeventlistener.asp
,
您需要将HTML与JavaScript分开。您可以将它们放在单独的文件中,也可以放在同一文件中。
如果您希望它们在同一文件中,则可以执行以下操作。 (注意:脚本必须位于按钮之后,因为我们希望它在创建按钮之后运行)
<button id="trainingbutton">Training Button</button>
<script>
var trainingbutton = document.getElementById("trainingbutton");
trainingbutton.addEventListener('click',function(event) {
trainingbutton.innerHTML = "Hello World";
});
</script>
您还可以在单独文件(* .js)中的脚本标签之间定义以上脚本,并使用<script src='*.js'></script>
将其链接到HTML文件。当您在HTML和JS中添加更多内容时,它可以帮助组织。