2017-07-29 100 views
1

我對JS中'this'的用法感到困惑。從w3cshoolThis.value與值,有什麼不同?

採取例如: https://www.w3schools.com/tags/tryit.asp?filename=tryhtml5_ev_onchange2

<!DOCTYPE html> 
 
<html> 
 
<body> 
 

 
<p>Modify the text in the input field, then click outside the field to fire the onchange event.</p> 
 

 
Enter some text: <input type="text" name="txt" value="Hello" onchange="myFunction(this.value)"> 
 

 
<script> 
 
function myFunction(val) { 
 
    alert("The input value has changed. The new value is: " + val); 
 
} 
 
</script> 
 

 
</body> 
 
</html>

如果我刪除 '本',它的工作原理也一樣,太糟糕了,我不能找到任何w3school教程來區分它。

在這種情況下,'this'是否會與'this'不同?

+1

https://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work也許這會有所幫助。 – Abhijeet

+0

+1給Abhijeet。作爲@Abhijeet建議的整體視圖,請參閱[本SO線程](https://stackoverflow.com/a/3127440/5909393)。 – Sidtharthan

回答

0

「this」是指函數的當前上下文或您正在使用的方法。因此,在您的示例中,這指的是輸入元素,因爲您輸入的值是從onchange事件輸入的,因此「this.value」將返回你輸入的任何內容。這裏有一個相關的stackoverflow問題,有一個很好的答案:What does "this" mean?

0

現在你可能已經明白,this隱式/顯式時,事件處理程序分配給一個元素。 但這個例子試圖強調甚至整個對象this可用並可以傳遞給事件處理程序的事實。有一個看看下面修改後的代碼:

<!DOCTYPE html> 
 
<html> 
 
<body> 
 

 
<p>Modify the text in the input field, then click outside the field to fire the onchange event.</p> 
 

 
Enter some text: <input type="text" name="txt" value="Hello" onchange="myFunction(this)"> 
 

 
<script> 
 
function myFunction(val) { 
 
    alert("The input value has changed. The new value is: " + val.value); 
 
    alert("The input value has changed. The new value is: " + val.type); 
 
} 
 
</script> 
 

 
</body> 
 
</html>

0

沒有爲代碼沒有區別,其爲on**** HTML屬性來定義。該代碼將可以訪問爲this對象的每個屬性定義的別名,因此您可以省略this.。這隻適用於直接分配給on屬性的代碼。這些別名在您可能從那裏調用的函數中將不再存在。

演示:

<div onclick="textContent='you clicked!';console.log(textContent)">click me</div>

相關問題