jQuery `this` 在用户函数中工作很奇怪
jQuery `this` works weird in user functions
请解释一下,为什么 this
自身和函数的行为不同?
(function ($) {
$.fn.wtf = function () {
// See in console
// `this` returns what expected
console.log(this);
// `this.html()` returns only the first element's content
console.log(this.html());
}
$('body').find(':header').wtf();
}(jQuery));
.html() returns 第一个匹配元素,所以通过使用 this.html() jQuery returns 它找到的第一个元素你的情况是 h1 顶部元素。
有关这方面的更多信息,请参阅文档:http://api.jquery.com/html/
希望这有助于回答您的问题。
请解释一下,为什么 this
自身和函数的行为不同?
(function ($) {
$.fn.wtf = function () {
// See in console
// `this` returns what expected
console.log(this);
// `this.html()` returns only the first element's content
console.log(this.html());
}
$('body').find(':header').wtf();
}(jQuery));
.html() returns 第一个匹配元素,所以通过使用 this.html() jQuery returns 它找到的第一个元素你的情况是 h1 顶部元素。
有关这方面的更多信息,请参阅文档:http://api.jquery.com/html/
希望这有助于回答您的问题。