简体   繁体   中英

Cache objects for onclick in javascript

Is there a reason to cache myId like below (let's say the object myId will only be used for this popup function, nowhere else in the JavaScript).

var myId = document.getElementById('myId');
myId.onclick = function () {
  alert('button was clicked');
}

I figure that the onclick event will only be set once and that it is unnecessary. But I'm not sure.

The only reason to cache would be if you would want to use the myid element for more than just binding the click event .

One often caches elements for just that reason, which saves performance because you dont have to search the DOM tree more than once.

通常,最好将元素缓存一次,直到您可能会再次使用它,但是如果您确定不需要再次访问它,则没有理由将其保存以供以后使用。

You're just assigning a variable that could possibly conflict with another down the track. If you're only setting the callback once, just do it like this:

document.getElementById('myId').onclick = function () {
    alert('button was clicked');
}

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