为什么" $(this)"在以下示例中不起作用

时间:2017-04-06 13:48:30

标签: javascript jquery

HTML:

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

的jQuery

$(function () {

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

});

为什么$(this)在这里不起作用?如果要包含多个元素(.test),例如3:if (!$(".test, .test2, .test3").val()) {

,可以做些什么呢?

1 个答案:

答案 0 :(得分:4)

问题是因为代码直接在document.ready处理程序中运行,因此属于document的范围,因此this引用document

为了达到你的要求,你最好缓存一个选择器并再次使用它来添加所需的类,如下所示:

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

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

如果要包含多个元素,例如3:if (!$(".test, .test2, .test3").val()) {

,有什么可以做的呢?

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

if (!$('.test1').val() && !$('.test2').val() && ... ) {
相关问题