问题描述
为什么建议不要在您的HTML中使用onclicks,在您的JS文件中使用事件处理程序被认为是最佳做法???
为什么建议不要在您的HTML中使用onclicks,在您的JS文件中使用事件处理程序被认为是最佳做法???
您只能在* 上使用的一个处理程序。
使用事件注册模型时,您可以将相同事件附加到相同元素的处理程序数量限制为
。另外,它有助于整合Javascript中的所有行为,而不是遍及整个代码库。
// HTML
// Javascript
var el = document.getElementById(somePara);
el.onclick = function(){
alert(Second);
};
el.onclick = function(){
alert(Third);
};
//当< p>被点击,它提醒第三,覆盖前两个处理程序。
相反,更好的方法是使用事件注册。继续上面的例子(这只是为了演示,而不是跨浏览器),
el.addEventListener(click,函数(){
alert(Un);
});
$ b el.addEventListener(click,function(){
alert(Dos);
});
//点击< p>现在会提醒第三,联合国和Dos。
Why its recommended not use onclicks in your HTML.Use Event Handlers in your JS file is considered as best practice???
You can only have one handler with on*
.
But no limits on the number of handlers you can attach to the same element for the same event when using the event registration model.
Besides, it helps consolidate all behavior within Javascript and not sprinkled throughout the codebase.
Note: you can attach events using on* inside your Javascript as well. The DOM event registration model was introduced to fix this very problem. See this example for more information:
// HTML
<p id="somePara" onclick="alert('First')">...</p>
// Javascript
var el = document.getElementById("somePara");
el.onclick = function() {
alert("Second");
};
el.onclick = function() {
alert("Third");
};
// when <p> is clicked, it alerts "Third", overwriting the first two handlers.
Instead, a better approach is to use the event registration. Continuing the above example (this is just for demonstration and it's not cross-browser),
el.addEventListener("click", function() {
alert("Un");
});
el.addEventListener("click", function() {
alert("Dos");
});
// clicking on the <p> will now alert "Third", "Un", and "Dos".
这篇关于为什么建议不要在您的JS文件的HTML.Use事件处理程序中使用onclicks的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!