Javascript 如何按特定文本获取下拉列表项(不区分大小写)
我曾与J-Query合作,但在获取期权价值时遇到问题。 我想得到一个有特定文本的选项(文本不区分大小写)。 我使用了以下代码- 我的Html代码是- 当运行这段代码时,我得到了正确的结果。但是当按照Jquery代码运行时,我得到了Javascript 如何按特定文本获取下拉列表项(不区分大小写),javascript,jquery,contain,Javascript,Jquery,Contain,我曾与J-Query合作,但在获取期权价值时遇到问题。 我想得到一个有特定文本的选项(文本不区分大小写)。 我使用了以下代码- 我的Html代码是- 当运行这段代码时,我得到了正确的结果。但是当按照Jquery代码运行时,我得到了未定义的 $('#ddlStateList_CA option:contains("manitoba")').val(); 我知道Manitoba和Manitoba是不一样的,但是如果我想在这两种情况下都做这项工作的话 我该怎么做 使用过滤器 $(
未定义的
$('#ddlStateList_CA option:contains("manitoba")').val();
我知道Manitoba
和Manitoba
是不一样的,但是如果我想在这两种情况下都做这项工作的话
我该怎么做
使用过滤器
$('#button').click(function() {
console.log($("select option").filter(function() {
return $(this).text().toLowerCase() === 'manitoBa'.toLowerCase();
}).text());
});
我的文件中有一个函数,可以做你想做的事情。加载jQuery后添加以下内容:
if(jQuery){
(function($){
//@Author Karl-André Gagnon
if(!$.fn.filterText) $.fn.filterText = function(text, caseSensitive){
var returnedObj = $(),
caseSensitive = caseSensitive || false,
$this = $(this);
if(text instanceof Array){
for(var i = 0; i < text.length; i++){
if(typeof text[i] == 'string'){
returnedObj = returnedObj.add($this.filter(function(){
var search = caseSensitive ? text[i] : new RegExp(text[i], 'i')
return $(this).text().search(search) != -1;
}))
}else if(text[i] instanceof RegExp){
returnedObj = returnedObj.add($this.filter(function(){
return $(this).text().search(text[i]) != -1;
}))
}
}
}else if(typeof text == 'string'){
returnedObj = returnedObj.add($this.filter(function(){
var search = caseSensitive ? text : new RegExp(text, 'i')
return $(this).text().search(search) != -1;
}))
}else if(text instanceof RegExp){
returnedObj = returnedObj.add($this.filter(function(){
return $(this).text().search(text) != -1;
}))
}
return returnedObj;
}
})(jQuery)
}
其中false
表示“区分大小写”(默认值为false,因此实际上不需要)
或者用regexp调用它:
alert($('#ddlStateList_CA option').filterText(/manitoba/i).val());
Fiddle:使用一个简单的基于正则表达式的过滤器
var regexp = new RegExp('manitoba', 'i');
var val = $('#ddlStateList_CA option').filter(function(){
return regexp.test($(this).text())
}).val();
演示:您可能需要在if语句中与or运算符一起检查这两个选项。它工作不正常。我的控制台输出是-MB,MB,undefined@IshanJain应该是这样的,第一个o/p来自此代码,其他o/p是您的代码
alert($('#ddlStateList_CA option').filterText('manitoba', false).val())
alert($('#ddlStateList_CA option').filterText(/manitoba/i).val());
var regexp = new RegExp('manitoba', 'i');
var val = $('#ddlStateList_CA option').filter(function(){
return regexp.test($(this).text())
}).val();