📌  相关文章
📜  如何查找 jQuery 中所有为空的元素?

📅  最后修改于: 2021-11-24 04:35:07             🧑  作者: Mango

在本文中,我们将看到如何使用 jQuery 查找页面上所有为空的元素。

方法一: :empty选择器可以用来获取页面中当前为空的所有元素。这些元素使用each()方法进行迭代,并且可以使用循环内的this 引用进行访问。

可以通过在禁用选择器前面指定元素类型来选择特定类型的元素,否则页面上的所有元素都会被选中。例如,我们可以指定只检查 inputtextarea元素,如果它们为空。

句法:

$(".btn").on("click", function () {

    // Select all the empty elements on
    // the page and iterate through them
    $(":empty").each(function () {

        // Access the empty elements
    });
});

以下示例说明了上述方法:

例子:

HTML


  

    

  

    

        GeeksforGeeks     

                How to finds all elements         that are empty?             

        Click on the button to find         all empty elements     

                 

                 

            

       Empty Elements     
              


    HTML
    
    
      
    
        
    
      
    
        

            GeeksforGeeks     

                    How to finds all elements         that are empty?             

            Click on the button to find         all empty elements     

                     

                     

                     

           Your Order     
              
    •         
    • Item Two
    •         
    •         
    • Item Four
    •     
                      


    输出:

    方法2:首先使用jQuery选择器选择所有需要检查的页面元素。我们可以只指定inputtextarea元素,如果它们为空,则应该检查它们。然后循环遍历这些元素,然后使用is()方法检查当前元素是否与选择器匹配。 :empty选择器用于检查它是否为空,类似于第一种方法。

    句法:

    $(".btn").on("click", function () {
    
        // Select all the elements that
        // have to be checked and iterate
        // through them
        $("li, input, textarea").each(function () {
    
            // Check if the element is empty
            if ($(this).is(":empty"))
                // Access the empty element
            else
                // Access the non-empty element
        })
    });

    以下示例说明了上述方法:

    例子:

    HTML

    
    
      
    
        
    
      
    
        

            GeeksforGeeks     

                    How to finds all elements         that are empty?             

            Click on the button to find         all empty elements     

                     

                     

                     

           Your Order     
              
    •         
    • Item Two
    •         
    •         
    • Item Four
    •     
                      

    输出: