我有一个 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/