我与J查询一起工作,在获取选项值方面遇到了问题。我想得到有特定文本的选项(文本不区分大小写)。我用了以下代码-
我的Html代码是-
阿尔伯塔省、不列颠哥伦比亚省、马尼托巴省、新不伦瑞克省、纽芬兰省和拉布拉多西北地区新斯科舍省努纳武特省、安大略省爱德华王子岛、魁北克省萨斯喀彻温省育空省
Jquery代码-
$('#ddlStateList_CA option:contains("Manitoba")').val();当运行此代码时,我得到了正确的结果。但是,当按照Jquery代码运行时,我得到了undefined。
$('#ddlStateList_CA option:contains("manitoba")').val();我知道Manitoba和manitoba是不一样的,但是如果我想做这两种情况下的工作,我该如何做呢?
示例
发布于 2013-06-29 04:21:53
使用过滤器
$('#button').click(function() {
console.log($("select option").filter(function() {
return $(this).text().toLowerCase() === 'manitoBa'.toLowerCase();
}).text());
});JSFiddle
发布于 2013-06-29 04:24:04
使用一个简单的基于正则表达式的过滤器
var regexp = new RegExp('manitoba', 'i');
var val = $('#ddlStateList_CA option').filter(function(){
return regexp.test($(this).text())
}).val();演示:小提琴
发布于 2013-06-29 04:22:47
我的文件里有一个函数可以做你想做的事。在加载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)
}小型化版本: http://pastebin.com/hiJ4aw8x
那你就有多重选择了。你可以这样称呼它:
alert($('#ddlStateList_CA option').filterText('manitoba', false).val())哪个false表示"caseSensitive“(默认值为false,因此实际上不需要)。
或者用regexp调用它:
alert($('#ddlStateList_CA option').filterText(/manitoba/i).val());小提琴:http://jsfiddle.net/Cv8uC/6/
https://stackoverflow.com/questions/17376627
复制相似问题