代码之家  ›  专栏  ›  技术社区  ›  Hemant Maurya

正在读取dom id jquery方法

  •  -1
  • Hemant Maurya  · 技术社区  · 6 年前

    $(document).on('click', '.table .table_head1 a', function(e){
        e.preventDefault();
        alert($(this).attr('id'));
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
    <table class="table table-striped table-bordered">
        <thead>
            <tr>
                <th class="table_head1">
                    <a href="#" id="name">First Name
                    </a>
                </th>
            </tr>
        </thead>
    </table>

    如果我单击th/a,我想使用ID的名称,但是我写的上面的代码根本不起作用,它甚至没有检测到我单击了它。

    (是的,还包括jquery)

    2 回复  |  直到 6 年前
        1
  •  3
  •   Mamun    6 年前

    您缺少语法错误 ) 最后,除此之外,您的代码按预期工作。

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script type="text/javascript">
    
    $(document).on('click', '.table .table_head1 a', function(e){
       e.preventDefault();
       alert($(this).attr('id'));
    });
    
    </script>
    
    <table class="table table-striped table-bordered">
        <thead>
          <tr>
            <th class="table_head1">
              <a href="#" id="name">First Name
              </a>
            </th>
          </tr>
         </thead>
    </table>
        2
  •  2
  •   Colin    6 年前

    只使用 e.target.id $(this).attr('id') 以jquery的方式进行。

    正如我在评论中指出的,您的代码中有语法错误。

    $(document).on('click', '.table .table_head1 a', function(e) {
      e.preventDefault();
      alert('Vanilla JS: ' + e.target.id);
      alert('JQuery: '+ $(this).attr('id'));
    })
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <table class="table table-striped table-bordered">
      <thead>
        <tr>
          <th class="table_head1">
            <a href="#" id="name">First Name
              </a>
          </th>
        </tr>
      </thead>
    </table>