我试图通过用字符串替换每个单元格中的数据来格式化表的整个列。简单地说,如果我在输入字段中输入“nargles”并单击表格列顶部的格式按钮,那么该列中每个单元格中的文本都将替换为“nargles”。这工作正常。jQuery字符串替换匹配的正则表达式
我的问题涉及使用表值替换输入字符串中的“%0”,“%1”,“%2”等实例。 %0对应于第0列,第1列为%1,第2列为%2等。此外,它必须获取正在修改的当前行的列值。
为了用一个例子阐明,让我们表:
1 cat description
2 dog description
3 fish description
如果我进入“行%0%1”为我的输入和执行它的第3列,其结果将是:
1 cat Row 1 is for cat
2 dog Row 2 is for dog
3 fish Row 3 is for fish
希望这是一个足够的解释=)
所以,这里是示例表格内的样品:
<tr>
<td></td>
<td><button class="format" col="1">Format Col</button></td>
<td><button class="format" col="2" >Format Col</button></td>
</tr>
<tr>
<td><input type="text" col="0" row="0" value="0" size="1"></td>
<td><input type="text" col="1" row="0" value="cat" /></td>
<td><input type="text" col="2" row="0" value="description" /></td>
</tr>
...
,这里是在每列的顶部
$('td button.format').on('click', function() {
// get formatter variables and column number
string = $("#formatter").attr("value");
column = $(this).attr("col");
// regex to globally look for %d (where d is an integer)
var re = new RegExp("\%(\\d+)", "g");
$('td input[col="' + column + '"]').each(function (row) {
// replace string here
});
});
目前的格式按钮的代码,该代码结构将捕捉到的第一列的值,并能正常工作
$('td input[col="' + column + '"]').each(function (i) {
$(this).attr("value", string.replace(re, $('td input[col="1" row="' + i +'"]').attr('value')));
});
但这样做像这样(带有输入“%2”)将导致“undefined 2”。 (我用col="\$1"
替换了上面的col="1"
,并附加了“\ $ 1”以使用找到的第一个匹配的正则表达式)。我还应该注意到,除了“\ $ 1”之外,我用“$ 1”和“\ $ 1”没有运气。
$('td input[col="' + column + '"]').each(function (i) {
$(this).attr("value", string.replace(re, $('td input[col="\$1" row="' + i +'"]').attr('value') + " \$1"));
});
我的结论是,在该正则表达式匹配被代入的jquery查找和当执行查找时的时间是不正确的。由于结果是“未定义2”,我知道正则表达式匹配,但查找不正确。但是,我知道代码一般是正确的,因为硬编码col="2"
将起作用。
任何想法为什么这会遇到麻烦。我想说它的一个语法问题,但也许我错了。
旁注:如果我只是使用re.match()
函数并遍历返回的数组,这一切都可以避免。我知道一个解决方案存在,即时通讯只是看看是否有一个更优雅/更清洁的方式来做到这一点。
我知道这很长,对不起!我认为更多的信息比不够好。感谢您一路阅读!
您是充满了真棒。解决方案非常出色,你也向我介绍了jsfiddle,这看起来是一个很棒的网站。我在哪里送啤酒? – 2011-12-21 20:05:51
很高兴听到它的工作,@Scotty;) – georg 2011-12-22 09:54:58