簡體   English   中英

onclick處理程序中的this關鍵字不起作用

[英]The this keyword in onclick handler is not working

抱歉,如果很傻的話。 我無法在click事件中使this工作正常進行:

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

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

我想念什么?

您可以使用.call()

call()方法調用具有給定值的函數

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

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

要么

.bind()也可以使用。

bind()方法創建一個新函數,該函數在被調用時將其this關鍵字設置為提供的值,

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

您可以使用addEventListener代替我實際上建議的內聯處理程序。

 document.querySelector('div').addEventListener('click', function() { console.log(this.textContent); }) 
 <div> Click here! </div> 


除了call() / bind() ,您還可以像這樣傳遞this ,並且只需使用傳遞的參數即可。

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


該值this處理程序中

使用addEventListener()將處理程序函數附加到元素時,該值在處理程序內部的值是this元素的引用。 它與傳遞給處理程序的事件參數的currentTarget屬性的值相同。

如果在HTML源代碼中的元素上指定了事件屬性(例如onclick ),則屬性值中的JavaScript代碼將有效地包裝在處理程序函數中,該函數以與addEventListener()一致的方式綁定該值在代碼中出現this表示對該元素的引用。 請注意 ,在屬性值的代碼所調用的函數內部的this值的行為符合標准規則

Src: MDN

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM