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,我对在这个代码块中使用"this"感到困惑,在onchange EventHandler中。似乎"这"指的是选项元素,但我真的无法理解如何或为什么。
编辑:似乎不是那么基本。
我阅读了有关"这个"的一般问题的详细答案
"this"关键字如何工作?
还有很棒的文章:
http://www.digital-web.com/articles/scope_in_javascript/
他们两者都为很多人服务,但并不完全触及我的问题。
我无法弄清楚在 HTML 元素中使用带有 javascript 函数时"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
}
}
}