2011-12-21 75 views
3

我試圖通過用字符串替換每個單元格中的數據來格式化表的整個列。簡單地說,如果我在輸入字段中輸入「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()函數並遍歷返回的數組,這一切都可以避免。我知道一個解決方案存在,即時通訊只是看看是否有一個更優雅/更清潔的方式來做到這一點。

我知道這很長,對不起!我認爲更多的信息比不夠好。感謝您一路閱讀!

回答

5

我猜你正在尋找的東西是這樣的:

$('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/

+1

您是充滿了真棒。解決方案非常出色,你也向我介紹了jsfiddle,這看起來是一個很棒的網站。我在哪裏送啤酒? – 2011-12-21 20:05:51

+0

很高興聽到它的工作,@Scotty;) – georg 2011-12-22 09:54:58