簡體   English   中英

使用jQuery僅將數字環繞

[英]Wrap span around only numbers with jQuery

如何在帶有“數據”類而不是$字符的表格單元格中的數字(僅數字)周圍包裹一個span

這是HTML標記:

<table>
    <tr>
        <th>Description</th>
        <th>Weight</th>
        <th>Views</th>
        <th>Cost</th>
    </tr>

    <tr>
        <td>Item description here</td>
        <td class="data">37 pounds</td>
        <td class="data">132 views</td>
        <td class="data">$99.59</td>
    </tr>
</table>

您需要使用正則表達式來匹配數字,並用span包裹它們。

var rxp = new RegExp("([0-9]+\.?[0-9]+)", "gm");
$("td.data").each(function(){
    var $this = $(this);
    var content = $this.html();
    $this.html(content.replace(rxp, "<span>$1</span>"));
});

參見jsFiddle上的測試用例

您可以使用正則表達式:

var searchPattern = new RegExp(/^\d+$/, 'g');
$elem = $('td.data');
$elem.html($elem.html().replace(searchPattern , "<span>" + searchPattern  + "</span>"));

其中,$ elem是要搜索的HTML元素的jQuery對象,即所有TD類為“ data”的對象。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM