Объясните плз как работает this
Добрый день,
У меня есть фукция которая вызывается на select при onChange и этот же select имеет id="firstService" вот так у меня все работает function SelectService() { var e = document.getElementById("firstService"); var strUser = e.options[e.selectedIndex].getAttribute("countable"); console.log(strUser); } Я хочу отвязаться от id и переделать через this, что бы эту фукцию можно было вызывать на нескольких select Пробовал вот так function SelectService() { var strUser = this.options[this.selectedIndex].getAttribute("countable"); console.log(strUser); } но получил Uncaught TypeError: Cannot read property 'undefined' of undefined В чем я ошибаюсь, и как переделать фукцию что бы она работала через this? |
Bizon4ik,
onChange= SelectService(this); function SelectService(obj) { var strUser = obj.options[obj.selectedIndex].getAttribute("countable"); console.log(strUser); } |
<html> <head> <meta charset="utf-8"> </head> <body> <select id="s1"> <option countable=true>foo</option> <option countable=false>foo</option> </select> <select id="s2"> <option countable=true>foo</option> <option countable=false>foo</option> </select> <script> s1.onchange=s2.onchange=function() { with(this) console.log(options[selectedIndex].getAttribute("countable")) } </script> </body> </html> |
Часовой пояс GMT +3, время: 01:27. |