Regex jQuery find(“option:[text^='”]) 错误高于 即 8 和 chrome

Regex jQuery find("option:[text^='"]) error above ie 8 and chrome

本文关键字:错误 高于 chrome find jQuery option text Regex      更新时间:2023-09-26

我有一个jScript函数来文本搜索下拉列表中的元素。它曾经工作正常,直到 ie7。我有一个跨浏览器工作的解决方法,但在 ie7 中使用 jQuery 选项:包含而不是正则表达式很慢。

功能:

/// 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!
    });    
}

有人熟悉更好的解决方法吗?阅读的传统知识!

试试这个:

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);
}