简体   繁体   中英

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. The first one is just a

Option 1:

var ul = document.getElementById('inputField');
ul.onkeyup= function (event) {
    var target = getEventTarget(event);
    var userInput = target.value;
    alert(userInput );
};

Option 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. My question is... Is there one method that is frowned over the other?

Both are equally bad, and frowned upon (as is using jQuery). Use 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM