javascript - onclick 处理程序中的 this 关键字不起作用

标签 javascript html

如果很愚蠢,请道歉。我无法使 thisclick 事件中工作:

<div onclick='hello()'>
     Click here!
</div>

<script>
    function hello() {
        // I want to do some works with *this* object
        alert(this.textContent);
    }
</script>    

我错过了什么?

最佳答案

您可以使用.call()

The call() method calls a function with a given this value

<div onclick='hello.call(this)'></div>

<div onclick='hello.call(this)'>
  Click here!
</div>
<script>
  function hello() {
    console.log(this.textContent);

  }
</script>

或者

.bind()也可以使用。

The bind() method creates a new function that, when called, has its this keyword set to the provided value,

<div onclick='hello.bind(this)()'>
  Click here!
</div>
<script>
  function hello() {
    console.log(this.textContent);

  }
</script>

关于javascript - onclick 处理程序中的 this 关键字不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42222958/

相关文章:

javascript - 获取被 jQuery 更改后的 HTML 元素的内容

html - 小型设备上 Bootstrap 中的网格对齐

javascript - JavaScript 中的表

javascript - 删除 d3 中的特定 svg

javascript - SVG - 获取 TextElement 的字体大小

javascript - 为什么不触发 ondrop html 事件?

html - 使用 `enctype="multipart/form-data"` 总是还是从不?

javascript - 使用 jQuery/JS 定位元素,如粘性而不是使用位置粘性

javascript - 如何在 img 元素中使用 `data-text` 属性?

javascript - 在 Cordova 触发 deviceready 之前初始化应用程序