的onclick = QUOT;" vs事件处理程序
如果我想要执行一个函数,我更喜欢内嵌js:
If I want a function to be executed, I prefer doing inline js:
<p id="element" onclick="doSomething();">Click me</p>
因为它更容易调试。
但是,我听到有人说不要使用内联js,并且做:
However, I hear people saying not to use inline js, and do:
document.getElementById('element').onclick = doSomething;
为什么建议使用js事件监听器?
Why is the js event listener recommended?
基本上它与整体保持一切分离我相信。所以保持HTML / CSS / JS全部分开。它使您的HTML整洁,而且我认为更容易导航。
Basically it has to do with the whole keep everything separate I believe. So keep HTML/CSS/JS all separate. It makes your HTML tidier and, I think, easier to navigate without.
然后当/如果您需要进行大的更改,您有足够的空间必须转移将JS内联到外部文件,或者如果要对多个按钮应用相同的功能,那么它的代码较少。而较少的代码是一个更快乐的地方
Then when/if you need to make large changes, you have ample space with having to shift the inline JS to an external file anyway OR if you want to apply the same function to more than one button, then it's less code. And less code is a happier place
如果您的JS文件正确,并彻底记录,然后由外部人员导航他们是eaiser
If you have your JS files properly, and thoroughly documented then navigating them by an outside person is made eaiser