HTML ELEMENTS行为中Javascript中的“This”关键字[重复]
Posted
技术标签:
【中文标题】HTML ELEMENTS行为中Javascript中的“This”关键字[重复]【英文标题】:"This" Keyword in Javascript inside HTML ELEMENTS behavior [duplicate] 【发布时间】:2020-01-27 18:07:05 【问题描述】:th,td
padding: 5px;
</style>
<body>
<h2>The XMLHttpRequest Object</h2>
<form action="">
<select name="customers" onchange="showCustomer(this.value)">
<option value="">Select a customer:</option>
<option value="ALFKI">Alfreds Futterkiste</option>
<option value="NORTS ">North/South</option>
<option value="WOLZA">Wolski Zajazd</option>
</select>
</form>
<br>
<div id="txtHint">Customer info will be listed here...</div>
<script>
function showCustomer(str)
var xhttp;
if (str == "")
document.getElementById("txtHint").innerhtml = "";
return;
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function()
if (this.readyState == 4 && this.status == 200)
document.getElementById("txtHint").innerHTML = this.responseText;
;
xhttp.open("GET", "getcustomer.asp?q="+str, true);
xhttp.send();
</script>
</body>
</html>
嘿,很抱歉这个基本问题 :) 只是研究了一些 javascript 的 AJAX,我对在 onchange EventHandler 中的这个代码块中使用“this”感到困惑。似乎“this”指的是选项元素,但我无法真正理解如何或为什么。
编辑:似乎它不是那么基本。
我阅读了关于“this”的一般问题的详细答案
How does the "this" keyword work?
还有一篇很棒的文章:
http://www.digital-web.com/articles/scope_in_javascript/
他们都为很多人服务,但不要完全触及我的问题。
当在 HTML 元素中使用“this”时,我无法弄清楚它的确切行为是什么,并带有一个 javascript 函数。
希望有人能理解我的意思
【问题讨论】:
this
指的是xhttp
变量。因此,当响应返回时,您检查 xhttp.readyState
是否等于 4。副本包含完整说明。在 HTML 中,this.value
指的是所选选项元素的 value 属性。但是这两个this
es 不一样。
onreadystatechange 是 xhttp 的一个方法,所以当我们调用它时,“this”指的是 xhttp。阅读有关函数如何调用的更多信息
this
in onChange
showCustomer(this.value)
确实指的是具有 onClick 事件的元素。在其他上下文中,例如构造函数,它指的是正在构造的元素。
@MatteoTassinari 谢谢你,但我仍然找不到适合我情况的答案。
@Adder 你的答案是唯一一个至少触及我的问题的答案。你能详细说明一下吗?
【参考方案1】:
this指的是它所属的对象,例如
class dogs
constructor ()
this.name = 'dogs'
console. log(this.nane) // returns dogs
this.bread = function ()
console. log(this.name) // returns undefined
this.type = "pug"
console. log(this.type) // returns pug
console. log(this.type) // undefined
console. log(this.bread.type) // pug
【讨论】:
谢谢,但它不会攻击我的具体问题。以上是关于HTML ELEMENTS行为中Javascript中的“This”关键字[重复]的主要内容,如果未能解决你的问题,请参考以下文章