Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/68.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 解释js代码$(此)_Javascript_Jquery - Fatal编程技术网

Javascript 解释js代码$(此)

Javascript 解释js代码$(此),javascript,jquery,Javascript,Jquery,我有以下代码: // star/un-star $('.starred').on("click", function(event) { var inp = $(this) var user_id = $(this).data('user_id'); var current_value = $(this).data('value'); var new_value = current_value == '0' ? 1 : 0; $.post('/update_

我有以下代码:

// star/un-star
$('.starred').on("click", function(event) {
    var inp = $(this)
    var user_id = $(this).data('user_id');
    var current_value = $(this).data('value');
    var new_value = current_value == '0' ? 1 : 0;
    $.post('/update_starred/', {'user_id': user_id, 'new_value': new_value}, function (response) {
        inp.addClass('new')

    });
});

我注意到,如果要在post函数中使用该值,我必须定义
var inp=$(this)
。为什么它不在那里保留
$(this)
值?在post函数中,
$(this)
的值是多少?为什么?

在事件侦听器中,
指事件绑定到的事件目标。
$.post
回调可能有它自己的
。的可能重复,因为代码正在调用该对象上的函数:
inp.addClass('new')
,因此它需要对该对象的引用。由于它是在异步操作中发生的,
这个
的上下文到那时就丢失了。因此它首先将其存储在一个变量中。顺便说一句,只要您已经定义了
var inp=$(this)
,就应该去掉其他出现的
$(this)
,并在那里使用
inp
。把
这个
一次又一次地变成一个新的jQuery对象是没有意义的。根据我的经验,我会说有人用$this做了代码的第一部分,因为他不够关心。在那之后,他添加了需要post的功能,因为它被设置为不同的值,所以他创建了变量,但又一次没有注意将所有出现的变量替换到变量中。