A combination of AND and OR in jQuery selectors

2019-02-20 03:06发布

问题:

I have a jQuery selector with following syntax:

$('input[type=image]').not('.xyzClass').click(function{
    //some functionality
});

So this puts a specific click functionality for all the components which are of type image and does not have class xyzClass.

*****I have modified the question to reflect latest changes, some of the answers below are correct for previous version but may not hold correct for modified version. Apologies for that.

We need an OR condition with class condition. Such that Any component which is "input" having type as image, should be selected IF

  1. class is not xyzClassOR
  2. id contains string someIdString

Could you please help with the modification in existing selector?

Cheers.

回答1:

Updated answer

$('*:not(.xyzClass)[id*=containsThisValue]')

For your updated question, though this isn't optimized I would recommend specifying as much as you can.

Original answer:

function someSpecificFunctionality() {
}

$(els)

.click(someSpecificFunctionality)
.data('someSpecificFunctionality', true)


$(els).filter(function() {

    return 
        $(this).not('.xyzClass') && 
        $(this).data('someSpecificFunctionality') == true

});


回答2:

$(":image:not(.xyzClass),:image[onclick*='someSpecificFunctionality']");


回答3:

to do an "OR" use a comma:

$('input[type=image]')
    .not(".xyzClass,[onclick*='someSpecificFunctionality()']")
    .click(...);

I'm not sure how you're defining the onclick though: is it in your HTML or is added programmatically?