我正在尝试根据特定位置的用户定义值过滤零件号表。
参见 jsFiddle --> http://jsfiddle.net/bagofmilk/wx9F3/12/
问题是我允许多个条件 - 而不仅仅是一个位置的一个字符。
如果您看一下 fiddle ,您会发现我使用的是 Table Sorter 2.0 插件,效果很好。但我还在上面创建了一个带有 7 个文本框的小表格。这些文本框中的每一个都代表下表中零件号的一个值。
'data-log'
= 如果文本框为空,则值为 0,否则值为 1。
'data-val'
= 零件号字符串中的字符位置。
示例:如果用户在项目# 2 中键入“07”,则脚本将需要过滤零件号在字符串中第 2 个字符位置为“0”且字符位置为“7”的表格字符串中的3
大多数过滤器会在整个字符串中搜索“07”,但我需要它特定于它的位置。
我还需要它,以便当用户还在项目#7 中输入“L”时,脚本将过滤“07”位于字符位置 2,3 且“L”位于字符位置的部件号字符串中的 11。
这是我要处理的主要功能:
$('.modx').keyup(function() {
//I emtpy the "values" array and "position" array
arrval = [];
arrpos = [];
//Whatever textbox the user types in must indicate there is a value
$(this).attr('data-log', '1');
//I create an array of user input values and their positions
$('.modx').each(function() {
if ($(this).attr('data-log') == 1) {
arrval.push($(this).val());
arrpos.push($(this).attr('data-val'));
} else {}
});
/* THIS IS WHERE IM STUCK...Using the "values" array and "position" array,
check each part number where all values and positions are true.
I CANNOT COME UP WITH THE LOGIC HERE... */
});
我可能以完全错误的方式处理这个问题。如果是这样,我很想听听任何其他方法,或者如果您能想到我可以在此 keyup 函数末尾应用的逻辑,那也很棒。
最佳答案
这是一个基于正则表达式的解决方案
向第二个和第五个 modx 文本字段添加额外的 data-* 属性数据长度,如下所示
<input type='text' data-log='0' data-val='1' tabindex='2' placeholder='03' class='size2 modx' id='item2' data-length="2"/>
....
<input type='text' data-log='0' data-val='7' tabindex='6' placeholder='53'class='size2 modx' id='item6' data-length="2"/>
然后
var $modxs = $('.modx').keyup(function () {
var string = $modxs.map(function () {
var value = $.trim(this.value),
length = $(this).data('length') || 1;
while (value.length < length) {
value += '.';
}
return value;
}).get().join('');
string = string.replace(/(.{3})(.{5})(.{1})/, '$1-$2-$3');
var regex = new RegExp(string, 'i');
$('#partNumbers tbody tr').hide().filter(function () {
return regex.test($.trim($(this).children().first().text()))
}).show()
});
$('#clearBtn').click(function(){
$modxs.val('');
$('#partNumbers tbody tr').show()
})
演示:Fiddle
关于javascript - jquery根据特定位置的特定字符过滤值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21565771/