0

first situation:

<span id="username" onclick="alert(this.innerHTML);">[Василий]</span>

after click on text "[Василий]" i see text in dialog window "[Василий]". OK. But in second situation when I'd written code below I saw "undefined", why?

<script type="text/javascript" charset="utf-8">
        function func() {
        alert(this.innerHTML);
    }
</script>
     <span id="username" onclick="func();">[Василий]</span>
  • 1
    In second situation, there no exists the same scope as first. So there is no reference for this DOM like definition in HTML. The scope defined is the custom function. So this refered in second option, this to the scope of function and in first the scope got DOM. – Álvaro Touzón Feb 21 '17 at 07:56
  • `Inside a function, the value of this depends on how the function is called.` Refer, https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/this – RaR Feb 21 '17 at 07:58
  • thanks, I've understood now) – Александр Копаевич Feb 21 '17 at 08:11

1 Answers1

0

Basically you have no reference to the object, you clicked on. You could take this as parameter and get the value in the function.

function func(t) {
    alert(t.innerHTML);
}
<span id="username" onclick="func(this);">[Василий]</span>
Nina Scholz
  • 323,592
  • 20
  • 270
  • 324