将this关键字与selectedIndex一起使用的优势

Advantage to using the this keyword with selectedIndex?

本文关键字:一起 this 关键字 selectedIndex      更新时间:2023-10-26

这有什么好处吗:

document.getElementById('mySelectBox').options[this.selectedIndex].value

超过这个:

document.getElementById('mySelectBox').options[selectedIndex].value

只是好奇。谢谢

是的,如果不使用this,您将访问一个变量,而不是对象中的属性。

Javascript不是面向对象的,所以你永远不在对象的范围内,在那里你可以访问属性而不指定它们属于哪个对象

无论如何,如果this指的是元素,只需使用:

this.options[this.selectedIndex].value