jQuery selector, contains to equals

2019-01-18 09:39发布

问题:

I have the folowing selector

    var likeComperssionOption = $('select[id*=ComparisionType]').eq(0)
                                            .find("option:contains('LIKE')");

this checks for an option which contains the word 'like' right?

How do i find an option which is exactly with the word 'like'?

Somthing like this:

     var likeComperssionOption = $('select[id*=ComparisionType]').eq(0)
                                            .find("option:equals('LIKE')");

回答1:

Just select all the options from the select and filter them by text() value:

var likeComperssionOption = $('select[id*=ComparisionType]:first option').filter(function() { return $(this).text() == "LIKE" });


回答2:

If you want to select based on the value attribute of the options, you need to use the attribute equals selector to select elements with a specific value for their value attribute:

var likeComperssionOption = $('select[id*=ComparisionType]').eq(0)
                           .find("option[value='LIKE']")

Otherwise, to select based on the display text of the options, use:

var likeComperssionOption = $('select[id*=ComparisionType]').eq(0)
                           .find("option").filter(function() {
                               return $(this).text() == 'LIKE';
                           });

Update: You might be having some problems with your initial selector, it looks very strange. You should probably change

$('select[id*=ComparisionType]').eq(0)

to something simple like

$('#ComparisionType')

The concept of this answer works fine, you can see it in action here.