开发者

how to use regex on in a find function in jquery

I have the following statement:

if ($(this).find("option[text='My Cool Option1']").is(":selected"))
  //do something

basically I have a combobox with many options.开发者_StackOverflow I want to do something for options that start with My Cool Option<any number>

above code works for only one option My Cool Option1...but how do I make it work for say My Cool Option2 ..3..4 etc.


The ^= operator matches text at the start of the attribute, but it won't check that the rest is a valid number as such (is that important?). In theory:

if ($(this).find("option[text^='My Cool Option']").is(":selected"))

However! There is no text attribute on option, so both this and your original code shouldn't work. It only does work because of how jQuery fetches attribute values (fetching the text property instead of the text attribute), which is trying to work around some different browser bugs. This will definitely break in the future (if nothing else, when Selectors-API Level 2 is implemented in browsers and jQuery uses that in preference to its own code).

You could try the jQuery-specific non-standard contains selector:

if ($(this).find('option:contains("My Cool Option")').is(":selected"))

but this could match that string elsewhere in the text, if that matters.

If you've got a non-multiple selectbox (ie. only one option may be selected), you can fetch the one selected option's text() and check it:

if ($(this).find('option:selected').text().match(/^My Cool Option\d+$/))

otherwise, you'd have to iterate the options looking for the match:

var cool= false;
for (var i= this.options.length; i-->0;) {
    var option= this.options[i];
    if (option.selected && option.text.match(/^My Cool Option\d+$/)) {
        cool= true;
    }
}
if (cool) ...

(It's normally best to be checking option values rather than text strings though.)


There are plugins which extend the regex capabilities of JQuery such as this one from James Padolsey.

Keep in mind that this method can be slow so use with caution and only on limited element sets.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜