简体   繁体   English

什么时候应该使用on * DOM属性和on * HTML属性?

[英]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.

相关问题 为什么HTML DOM属性也应该反映到HTML DOM属性中? - Why should HTML DOM properties be reflected into HTML DOM attributes as well? 我应该使用HTML属性或类来指定输入字段的状态吗? - Should I use HTML attributes or classes to specify state on input fields? 我什么时候应该使用 `publishReplay` 和 `shareReplay`? - When should I use `publishReplay` vs `shareReplay`? 添加到 DOM 的元素具有 HTML / SVG 属性,但没有相应的 JS 属性 - Element added to DOM has HTML / SVG attributes, but not the corresponding JS properties 在创建Web小部件时,我应该在容器div上使用数据属性,还是应该在脚本中添加参数? - When creating a web widget should i use data attributes on the container div or should i add parameters to the script? nodejs:什么时候应该使用`setImmediate(cb)`vs`cb()`? - nodejs: When should I use `setImmediate(cb)` vs `cb()`? 我何时应该使用KnockoutJS组件与模板? - When should I use KnockoutJS Components vs. Templates? 我什么时候应该使用变量vs原始值? - When should I use a variable vs a raw value? 我什么时候应该使用call()vs直接调用函数? - When should I use call() vs invoking the function directly? 我什么时候应该在 redux-saga 中使用 yield* 与 yield? - When should I use yield* vs yield in redux-saga?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM