简体   繁体   English

如何 select JQuery 中具有特定类型的所有 div?

[英]How to select all divs with a specific type in JQuery?

I have some divs in my HTML-code with the type "button" (see code below).我的 HTML 代码中有一些 div 类型为“按钮”(参见下面的代码)。 How do I select all of these buttons and add a click-listener to them in JQuery?我如何 select 所有这些按钮并在 JQuery 中向它们添加点击侦听器?

<div class="container">
      <div lass="row">
        <div type="button" id="green" class="btn green"></div>

        <div type="button" id="red" class="btn red"></div>
      </div>

      <div class="row">
        <div type="button" id="yellow" class="btn yellow"></div>
        <div type="button" id="blue" class="btn blue"></div>
      </div>
    </div>

Here is one of the things I have tried:这是我尝试过的事情之一:

$('[class*="btn"]').click(function () {
  console.log("Method called!");
  $(this).addClass("pressed");
  setTimeout(function () {
    $(this).removeClass("pressed");
  }, 50);

}

Change改变

$('[class*="btn"]').click(function () {

to

$('.btn').click(function () {

However, it's not ideal binding the same event to multiple elements - this will lead to performance issues once you get to a decent number of elements.然而,将同一个事件绑定到多个元素并不理想——一旦你得到相当数量的元素,这将导致性能问题。 Instead, delegate the event to a parent.相反,将事件委托给父级。

$('.container').on('click', '.btn', function () {

Try this as your JS code:试试这个作为你的 JS 代码:

$('.btn').click(function () {
  console.log("Method called!");
  $(this).addClass("pressed");
  var elem = $(this); // Use elem inside setTimeout function
  setTimeout(function () {
    elem.removeClass("pressed");
  }, 50);

});

I think that type attribute can't be used with divs.我认为 type 属性不能与 div 一起使用。 Try using classes or actual buttons.尝试使用类或实际按钮。 Btw, if type could work with divs, jquery would look like div[type="button"]顺便说一句,如果 type 可以与 div 一起使用,jquery 看起来像 div[type="button"]

With jQuery you can select elements using CSS attribute selector.使用 jQuery 您可以使用 CSS 属性选择器来 select 元素。

 $('div[type="button"]').on('click', function() { console.log('clicked'); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="container"> <div lass="row"> <div type="button" id="green" class="btn green">Button 1</div> <div type="button" id="red" class="btn red"></div> </div> <div class="row"> <div type="button" id="yellow" class="btn yellow">Button 2</div> <div type="button" id="blue" class="btn blue">Button 3</div> </div> </div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM