简体   繁体   中英

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). How do I select all of these buttons and add a click-listener to them in 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:

$('.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. Try using classes or actual buttons. Btw, if type could work with divs, jquery would look like div[type="button"]

With jQuery you can select elements using CSS attribute selector.

 $('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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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