Javascript-форум (https://javascript.ru/forum/)
-   Events/DOM/Window (https://javascript.ru/forum/events/)
-   -   Объясните плз как работает this (https://javascript.ru/forum/events/58026-obyasnite-plz-kak-rabotaet.html)

Bizon4ik 01.09.2015 00:00

Объясните плз как работает 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?

рони 01.09.2015 00:03

Bizon4ik,
onChange= SelectService(this);
function SelectService(obj)
  {
    var strUser = obj.options[obj.selectedIndex].getAttribute("countable");
    console.log(strUser);
  }

forwardonly2015 01.09.2015 01:14

<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.