简体   繁体   中英

jQuery - Selector to run a function

How would I use the following code to run a function on any div with the class of .p11button which also has display:block ?

if (VARIABLE = true) {
    $('div .p11-button').css('display') == 'block'
    FUNCTION HERE
}

Try the following:

if (VARIABLE) {
  $('div.p11-button').filter(function() {
   return $(this).css('display' === 'block');
  }).each(function() {
    var self = $(this);
    //FUNCTION HERE
  });
}

In your code example you were assigning variable to true in the condition - this would always evaluate to true! Also, the space in your selector means you will select descendents of divs with class p11-button.

You can select elements by their attributes using square brackets:

$('div.p11-button[style*="display:block"]').css('color', 'red');

Here is a demo: http://jsfiddle.net/2uE4s/

This will select all div elements with the p11-button class and include display:block in their style attribute (just for example purposes I then change the CSS color property for all the selected elements to show that you don't need an .each() ).

Here is the documentation for selectors in jQuery: http://api.jquery.com/category/selectors/

像这样的东西?

$('div .p11-button').filter('[style*=display:block]').each(/*function*/);

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