下面两段代码在jQuery的官网见到的,何时用$(this),又何时用this呢?
$(document).ready(function() {
$("#orderedlist li:last").hover(function() {
$(this).addClass("green");
},function(){
$(this).removeClass("green"); # $(this)
});
});
$(document).ready(function() {
// use this to reset several forms at once
$("#reset").click(function() {
$("form").each(function() {
this.reset(); # this
});
});
});
Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
this是html元素对象吧~
$(this)成为jQuery对象
this 是 JavaScript 中的关键字。
$(this) 可以认为是用 jQuery 包装过 JavaScript 中的 this,包装后 $(this) 就会继承 jQuery 的方法。
$('a').click(function(){ // 这里的 this 指向当前点击的DOM节点,也就是a。可以调用DOM方法,比如this.getAttribute, this.tagName ... // 这里的 $(this) 表示包装过的一个 jQuery 对象,拥有 jQuery 的一些方法,比如 $(this).addClass(), $(this).hide() ... });$(this)是jquery对象,能调用jquery的方法,例如click(), keyup()。
而this,则是html元素对象,能调用元素属性,例如this.id,this.value。
例如假设已经使得this和$(this)都指向了input对象了,若要获得input的值,可以this.value,但$(this)就得$(this).val()。