首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >正则表达式jQuery find("option:[text^='"])在ie 8和chrome上出现错误

正则表达式jQuery find("option:[text^='"])在ie 8和chrome上出现错误
EN

Stack Overflow用户
提问于 2013-11-13 17:03:20
回答 1查看 285关注 0票数 1

我有一个jScript函数用来在下拉列表中搜索元素。在ie7之前,它一直运行得很好。我有一个解决办法,可以跨浏览器工作,但在ie7中使用jQuery选项会很慢:包含而不是正则表达式。

功能:

代码语言:javascript
复制
/// For the dropdown element passed, find the index where the Text  matches the passes string
/// and select this option. Returns true if found otherwise false

function selectTextinDropdown(el, sometext) {

    // Use REgex instead of option:contains as it it much faster!
   $(el).find("option:[text^='" + sometext.trim() + "']").each(function () {

   // works ok but SLOW in IE 7!!
   // $(el).find("option:contains('" + sometext.trim() + "')").each(function () {

      //alert("found|" + this.text + "|" + sometext);

        $(this).attr("selected", "selected");
        if ($(this).text() == sometext) {            
            $(this).attr("selected", "selected");
            return true; //found and selected!
        }
        return false; //Not found and Not  selected!
    });    

}

有谁熟悉更好的解决方法吗?tks阅读!

EN

回答 1

Stack Overflow用户

发布于 2013-11-21 09:01:37

试试这个:

代码语言:javascript
复制
function selectTextinDropdown(selectEle, targetText) {
  if(targetText==null){
    return false;
  }
  targetText = targetText.trim();

  // Find all options that meet your condition
  var $matches = $(selectEle).find('option').filter(function(index){
    // only use jquery selector once
    var $this = $(this);

    // extract text from the option
    var text= $this.text();

    // determine if it's found
    // OPTION A: exact match
    var found = (text === targetText);
    // OPTION B: partial match
    // var found = (text.indexOf(targetText) >= 0);

    if(found){ // select item if found
      $this.attr("selected", "selected");
    }
    return found;
  });

  return ($matches!=null && $matches.length>0);
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/19949500

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档