[英]jQuery string replace matched regex
我試圖通過用字符串替換每個單元格中的數據來格式化表的整個列。 簡單地說,如果我在輸入字段中輸入“nargles”並單擊表格列頂部的格式按鈕,則該列中每個單元格中的文本將替換為“nargles”。 這工作正常。
我的問題涉及用表值替換輸入字符串中的“%0”,“%1”,“%2”等實例。 %0對應於第0列,%1表示第1列,%2表示第2列,等等。此外,它必須獲取正在修改的當前行的列值。
為了澄清一個例子,讓我們拿表:
1 cat description
2 dog description
3 fish description
如果我為輸入輸入“Row%0 for%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
});
});
目前,此代碼結構將捕獲第1列的值並正常工作
$('td input[col="' + column + '"]').each(function (i) {
$(this).attr("value", string.replace(re, $('td input[col="1" row="' + i +'"]').attr('value')));
});
但是做這樣的事情(輸入“%2”)將導致“未定義2”。 (I取代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()
函數並迭代返回的數組,則可以避免這一切。 我知道存在一個解決方案,我只是看看是否有更優雅/更清潔的方式來做到這一點。
我知道這很長,抱歉! 我認為更多的信息比不夠好。 感謝您一路閱讀!
我想你正在尋找這樣的東西:
$('td button.format').click(function () {
var template = "Row %0 is for %1";
var col = $(this).attr("col");
$("#body tr").each(function() {
var $row = $(this);
var t = template.replace(/%(\d+)/g, function($0, $1) {
return $row.find("td:eq(" + $1 + ") input").val();
});
$row.find("td:eq(" + col + ") input").val(t)
})
})
完整示例: http : //jsfiddle.net/TTjtU/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.