jQuery selector, contains to equals

房东的猫 提交于 2019-12-17 18:52:19

问题


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.



来源:https://stackoverflow.com/questions/7344220/jquery-selector-contains-to-equals

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!