gpt4 book ai didi

jquery - "this"如何引用JQuery中的DOM元素

转载 作者:行者123 更新时间:2023-12-01 00:06:53 25 4
gpt4 key购买 nike

function() {
return this === window // true
}()
$("h1").click(function() {
$(this).css({"color": "red"}) // "this" becomes DOM element(s) here.
})

JQuery 如何实现从 windowDOM 元素this 引用以进行此类回调调用?

最佳答案

一切都与范围有关!一般来说,当前作用域中绑定(bind)到 this 的对象是由当前函数的调用方式决定的,在执行过程中不能通过赋值来设置,并且每次函数调用时都可以不同叫。

EcmaScript 5 引入了 bind 方法来修复函数的 this,无论它是如何调用的。

this 关键字出现在函数内部时,其值取决于函数的调用方式。

function() {
return this === window // true, "this" would be the window
}

function f2(){
"use strict";
return this; // "this" would return undefined in strict mode
}

var o = {
prop: 'test',
f: function() {
return this.prop; // here "this" would be the object o, and this.prop
// would equal o.prop
}
};

var t = o.f(); // t is now 'test'

jQuery使用call()apply()在一定范围内改变this的值,就像这样完成:

function add(c, d){
return this.a + this.b + c + d;
}

var o = {a:1, b:3};

// The first parameter is the object to use as 'this',
//subsequent parameters are passed as
// arguments in the function call
add.call(o, 5, 7); // 1 + 3 + 5 + 7 = 16

// The first parameter is the object to use as 'this',
// the second is an array whose members are used
//as the arguments in the function call
add.apply(o, [10, 20]); // 1 + 3 + 10 + 20 = 34

您可以阅读更多关于 this 的内容。 , call() , apply()和其他事情 MDN !

关于jquery - "this"如何引用JQuery中的DOM元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15819647/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com