为何选择“$(this)”在以下示例中不起作用 [英] Why "$(this)" doesn't work in the following example

查看:70
本文介绍了为何选择“$(this)”在以下示例中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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()){

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()) {

推荐答案

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

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.

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

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");
  }
});




有什么可以做的,如果超过要包含的一个元素,例如3: if(!$(。test,。test2,。test3)。val()){

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

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

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

这篇关于为何选择“$(this)”在以下示例中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆