簡體   English   中英

jQuery:檢查數據過濾器並替換空格

[英]jQuery: check data-filter and replace spaces

我正在嘗試讓jQuery檢查此列表內的所有數據過濾器,以防萬一它在單詞之間找到一個空格,應將其替換為“,”。 (我需要那些是類)。

這是我嘗試過的方法,但是當我檢查控制台時,它說“替換不是功能”。

HTML

<ul class="filter-list" data-option-key="filter">
    <li>
        <a data-filter=".class one" class="" href="#filter">class one</a>
    </li>
    <li>
        <a class="" href="#filter" data-filter=".class two">class two</a>
    </li>
    <li>
        <a class="" href="#filter" data-filter=".class three">class three</a>
    </li>
</ul>

jQuery的

$('.filter-list a[data-filter]').each(function () {
    $(this).replace(/\s/g,", .");
});

基本上,當jQuery找到“ .class three”時,應將其替換為“ .class .three”。

您可以使用.attr()來做到這一點

$('.filter-list a[data-filter]').attr('data-filter', function (i, attr) {
    return attr.replace(/\s+/g, ", .");
});

演示: 小提琴

您的代碼失敗,因為在each()處理函數中, this指向dom元素,而$(ths)返回一個沒有replace方法的jQuery對象。

在您的代碼中:

$('.filter-list a[data-filter]').each(function () {
  $(this).replace(/\s/g,", .");
});

$(this)是一個DOM元素。 您可以通過$(this).text()獲得文本。 因此您的代碼可以是這樣的:

$('.filter-list a[data-filter]').each(function () {
  $(this).text($(this).text().replace(/\s/g,", ."));
});

暫無
暫無

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

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