javascript - Regex jQuery find ("option:[text^=' "]) 在 ie 8 和 chrome 上出现错误

标签 javascript jquery html regex dom

我有一个 jScript 函数来文本搜索下拉列表中的元素。以前一直工作得很好,直到ie7。我有一个跨浏览器工作的解决方法,但在 ie7 中使用 jQuery 选项速度很慢:contains 而不是 Regex。

功能:

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

关于javascript - Regex jQuery find ("option:[text^=' "]) 在 ie 8 和 chrome 上出现错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19949500/

相关文章:

javascript - 仅用 RegEx 替换字符串中的外部标记

javascript - 希望使用 JS 或 jquery 将 "itemprop"标记添加到 div 中

html - 在可点击链接上叠加透明图像

javascript - 使用 jQuery html() 时在 html 中显示的特殊字符

javascript - 在 React Native Webview 中使用本 map 片

javascript - closure-compiler-js 和 grunt

javascript - 根据查询字符串生成动态超链接

javascript - 将按钮与 ui-modal 对话框的右上角重叠

javascript - 数据表不加载 JSON 数据,显示消息 "No data available in table"

jQuery Pagination - 如何适应不同的格式