1

我有一个 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!
    });    

}

有人熟悉更好的解决方法吗?谢谢阅读!

4

1 回答 1

0

尝试这个:

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);
}
于 2013-11-21T01:01:37.183 回答