我正在使用DataTable,我正在尝试使用位于表格单元格中的select元素来处理某些过滤功能。
过滤的工作原理是在位于每列下方的输入字段中输入文本。然后,过滤器函数检查该列的所有单元格中的所选文本,如果在一个单元格中找不到匹配项,则隐藏相关行。
当表已加载时,它可以过滤表一次。问题是清除过滤器时,它不起作用。原因似乎与我正在将selectedIndex用于位于当前不可见的行中的选择DOM对象有关。
“qu_owner_xxx”是选择元素的ID。
var el1 = document.getElementById("qu_owner_4"); //Visible, works like a charm
console.log("ID 1 " + el1.id); //ID is printed
console.log("EL 1 " + el1.selectedIndex);
var el2 = document.getElementById("qu_owner_17"); //Hidden, returns null
console.log("ID 2 " + el2.id); //Not reaching here
console.log("EL 2 " + el2.selectedIndex) ; //Not reaching here
str = el.options[el.selectedIndex].text; //Just for showing how to get the string used for filtering later
问题是单元格的数据作为纯html传递给过滤器函数,而不是作为对象。我可以从 $(aData [i2])。attr('id')获取该部分的id,其中aData是表格行。但是使用jQuery似乎有一些与使用实际DOM对象(例如selectedIndex)相比无法达到的信息,特别是当你必须从html“重新创建”对象时。
如何从隐藏的选择框/行的选定值中获取文本?它甚至可能吗?
更新
我在jsfiddle中测试了我的理论,但实际上它可以从隐藏的行/选择中检索信息。但毫无疑问,在我的过滤功能中,未显示的行是失败的。
我的过滤功能(DataTable在过滤时调用此功能)
$.fn.dataTableExt.afnFiltering.push(
function( oSettings, aData, iDataIndex ) {
var ret = true;
//Loop through all input fields i tfoot that has class 'sl_filter' attached
$('tfoot .sl_filter').each(function(i, obj){
//$(this) can be used. Get the index of this colum.
var i2 = $("tfoot input").index($(this));
//Create regexp to math
var r = new RegExp($(this).val(), "i");
var str = "";
if(i2 == 5){//This is just during development, don't want to care about other columns with select element so just doing things on this column
//Here I just pick two id, one that I know is visible and one that is not
var el1 = document.getElementById("qu_owner_4"); //Visible, works like a charm
console.log("ID 1 " + el1.id); //ID is printed
console.log("EL 1 " + el1.selectedIndex); //selectedIndex is printed
var el2 = document.getElementById("qu_owner_17"); //Hidden, returns null
console.log("ID 2 " + el2.id); //Not reaching here
console.log("EL 2 " + el2.selectedIndex) ; //Not reaching here
//This is how I intended to get it working, but fail
var el = document.getElementById($(aData[i2]).attr('id'));
str = el.options[el.selectedIndex].text; //String to be used for comparing
}
/*Test to see if there is a match or if the input value is the default
(the initial value of input before it has any fokus/text) */
if(r.test(str) || $(this).val()=="Search"){
//Return true only exits this function
return true;
}else{
/*Return false returns both function an .each. Retain 'false' in a variable scoped
to be reached outside the .each */
ret = false;
return false;
}
});
//Return true or false
return ret;
}
);
aData =该行。 aData [x]给出了该行上单元格x的单元格内容。对于select元素,它是原始html。
this =输入搜索字符串的输入字段。
答案 0 :(得分:0)
当然,您可以从所选值中获取文本!
这是一种方式(可能不是最好的,但有效):
$('select').change(function() {
var selectedValue = jQuery(this).val();
var selectedText = '';
jQuery(this).children('option').each(function() {
if (jQuery(this).val() == selectedValue) {
selectedText = jQuery(this).text();
}
});
});
selectedText
变量将包含所选值的文本。
请参阅here。