代码之家  ›  专栏  ›  技术社区  ›  paul cappucci

如何在执行jquery之前检查类名是否存在

  •  0
  • paul cappucci  · 技术社区  · 7 年前

    在jquery执行之前,如何首先检查页面上是否存在类名?我知道你可以用length()方法来检查这个。现在,我的jquery在每一页上运行,如果我要更改的类名不在该页上,我就会出错。类型错误:未定义或空引用的“otable”。下面是我的代码。

        var oTable;
        jQuery( document ).ready( function($) {
          'use strict';
    
        if ($('.mytable2').length > 0) {// Run the code below only if the class mytable2 exists
    
         // start datatable
        oTable = $('.mytable2').DataTable( {
            pageLength: 10,
            searching: true
         });
        // end datatable
    
        // start yadcf
        yadcf.init(oTable, 
         [
          {
           column_number : 0,
           filter_container_id: 'external_filter_container1',
           filter_default_label: 'Select',
           }
          ]
         );
        // end yadcf
        }}); // end ready function and if mytable2 exists
    
    3 回复  |  直到 7 年前
        1
  •  0
  •   Mihai T    7 年前

    你的 if 条件应该有效。虽然我看不到 foo 在你的代码中。

    另一个解决方案是 hasClass .

    见下文

    if ($(".my-class").length > 0) {
      console.log('class exists')
    }
    
    if ($("table").hasClass('my-class')) {
      console.log('table has class')
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <table class="my-class">
    </table>
        2
  •  0
  •   Nikos M.    7 年前

    如果要检查类名是否已存在 之前 正在执行 jquery (甚至在装货前 JQuery 使用 document.getElementsByClassName .

    例如:

    if ( document.getElementsByClassName('mytable2').length ) {
        // class exists in document, handle accordingly
    }
    
        3
  •  0
  •   saif ullah    7 年前

    有两种解决办法。 1)将jquery引用放在HTML文档的头部分 2)或者将当前代码放在下面的共享布局或索引页中