jQuery:我们不能将jQuery(this)分配给变量吗?

时间:2016-01-07 08:28:31

标签: javascript jquery

我正在练习jQuery。如果这是一个奇怪的问题,请原谅我。

问题:我们可以将jQuery(this)分配给变量吗?

解释

我可以为变量分配各种jQuery选择器,然后我可以使用这些变量来调用不同的jQuery函数。

例如

    $filterSwitch = jQuery('.filter-switch');

    $filterSwitch.click(function(e) {
       alert("Filter Button Clicked"); // This works without any problem
    });

另一方面,在将其分配给变量后,我似乎无法使用jQuery(this)

例如

    $filterSwitch = jQuery('.filter-switch');
    $current = jQuery(this);

    $filterSwitch.click(function(e) {
       $current.toggleClass("filter-on"); // This does not work
       jQuery(this).toggleClass("filter-on"); // This works
    });

这是不允许的,还是有任何特定的方法将jQuery(this)分配给变量?

2 个答案:

答案 0 :(得分:6)

这是因为您需要记住$current = jQuery(this); 是指您当前所处的背景。

所以第一个

this

可能意味着第二个this以外的身体或其他东西。

第二个.filter-switch位于click方法的上下文中,并且该上下文设置为$filterSwitch = jQuery('.filter-switch'); $filterSwitch.click(function(e) { $filterSwitch.toggleClass("filter-on"); // This works for all elements with that class jQuery(this).toggleClass("filter-on"); // This works only for the one you're clicking atm });

希望这有道理:)

你可以这样做:

$timeout(function() {
  progressBar("delay");
}, 100);        

请注意,第一行现在指的是具有filter-switch类的所有元素,而第二行仅指向您正在处理的那一行。

答案 1 :(得分:1)

this是一个 DOM元素,jQuery将回调函数的范围设置为回调主题的元素。

此处this将是此处单击的元素,只能在处理程序的回调中使用this关键字进行访问。

$filterSwitch = jQuery('.filter-switch');
$current = jQuery(this);

$filterSwitch.click(function(e) {
  $current.toggleClass("filter-on"); // This does not work because when $current was assigned, `this` did not refer to the correct element.

  $newCurrent = jQuery(this); // Now `this` is the clicked element.
  $newCurrent.toggleClass("filter-on"); // This works
});
相关问题