【发布时间】: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 属性。但是这两个thises 不一样。 -
onreadystatechange 是 xhttp 的一个方法,所以当我们调用它时,“this”指的是 xhttp。阅读有关函数如何调用的更多信息
-
thisinonChangeshowCustomer(this.value)确实指的是具有 onClick 事件的元素。在其他上下文中,例如构造函数,它指的是正在构造的元素。 -
@MatteoTassinari 谢谢你,但我仍然找不到适合我情况的答案。
-
@Adder 你的答案是唯一一个至少触及我的问题的答案。你能详细说明一下吗?
标签: javascript html ajax dom