为什么“$(this)”在以下示例中不起作用[重复]

时间:2021-07-08 07:03:09

This question already has an answer here:

这个问题在这里已有答案:

HTML:

HTML:

<!-- try to change the value="" -->
<input class="test" type="text" value="">

jQuery

jQuery的

$(function () {

        if (!$(".test").val()) {
        alert("Empty");
            $(this).addClass("removeMe");
        } else {
        alert("not Empty");
            $(this).addClass("addMe");
        }

});

Why $(this) doesn't work here? And what is it possible to do about it if, say there's more than one element(.test) to include, for example 3: if (!$(".test, .test2, .test3").val()) {

为什么$(这个)在这里不起作用?如果要包含多个元素(.test),例如3:if(!$(“。test,。test2,。test3”)。val()){那么可以做些什么?

1 个解决方案

#1


4  

The problem is because the code runs directly within the document.ready handler and is therefore within the scope of the document, hence this refers to the document.

问题是因为代码直接在document.ready处理程序中运行,因此属于文档的范围,因此这指的是文档。

To achieve what you require you would be best to cache a selector and use that again to add the required class, like this:

要实现您的需求,最好缓存一个选择器并再次使用它来添加所需的类,如下所示:

$(function () {
  var $test = $('.test');

  if (!$test.val()) {
    console.log("Empty");
    $test.addClass("removeMe");
  } else {
    console.log("not Empty");
    $test.addClass("addMe");
  }
});

What is it possible to do about it if, say there's more than one element to include, for example 3: if (!$(".test, .test2, .test3").val()) {

如果要包括多个元素,例如3:if(!$(“。test,。test2,。test3”)。val()){那么可以做什么呢?

In that case you'd need to test each element individually:

在这种情况下,您需要单独测试每个元素:

if (!$('.test1').val() && !$('.test2').val() && ... ) {

#1


4  

The problem is because the code runs directly within the document.ready handler and is therefore within the scope of the document, hence this refers to the document.

问题是因为代码直接在document.ready处理程序中运行,因此属于文档的范围,因此这指的是文档。

To achieve what you require you would be best to cache a selector and use that again to add the required class, like this:

要实现您的需求,最好缓存一个选择器并再次使用它来添加所需的类,如下所示:

$(function () {
  var $test = $('.test');

  if (!$test.val()) {
    console.log("Empty");
    $test.addClass("removeMe");
  } else {
    console.log("not Empty");
    $test.addClass("addMe");
  }
});

What is it possible to do about it if, say there's more than one element to include, for example 3: if (!$(".test, .test2, .test3").val()) {

如果要包括多个元素,例如3:if(!$(“。test,。test2,。test3”)。val()){那么可以做什么呢?

In that case you'd need to test each element individually:

在这种情况下,您需要单独测试每个元素:

if (!$('.test1').val() && !$('.test2').val() && ... ) {