[英]When should I use on* DOM properties vs on* HTML attributes?
So I have the option of using the 2 implementations below to keep track of which li element was clicked. 因此,我可以选择使用下面的2个实现来跟踪单击了哪个li元素。 The first one is just a 第一个只是一个
Option 1: 选项1:
var ul = document.getElementById('inputField');
ul.onkeyup= function (event) {
var target = getEventTarget(event);
var userInput = target.value;
alert(userInput );
};
Option 2: 选项2:
<input id="inputField" onkeyup="alert(userInput)" />
I understand that in the case above, the shorter one is more attractive. 我了解在上述情况下,越短越有吸引力。 However, if I plan to use several input fields, option 1 is more attractive as I won't have to take code every single attribute for each input field. 但是,如果我打算使用多个输入字段,则选项1更具吸引力,因为我不必为每个输入字段的每个属性输入代码。 My question is... Is there one method that is frowned over the other? 我的问题是...有一种方法不适合另一种方法吗?
Both are equally bad, and frowned upon (as is using jQuery). 两者都同样糟糕,并且皱着眉头(就像使用jQuery一样)。 Use addEventListener
. 使用addEventListener
。
ul.addEventListener("keyup", function () {
// callback
});
If you want to be compatible with older browsers add a wrapper that check for addEventListener
with a fallback to attachEvent
. 如果要与较旧的浏览器兼容,请添加一个包装器,以检查addEventListener
并回attachEvent
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.