从段落元素中切出第一个字符,替换内容并添加类。 jQuery的

时间:2013-09-24 11:14:17

标签: javascript jquery replacewith

我接近让这个功能正常工作,但还没有完成。

基本逻辑说找到任何包含“+”的p元素,从文本中删除“+”并尝试用新内容替换现有内容并添加一个类。

最初,我将所有匹配的元素都返回并连接成一个段落。所以我试着创建一个函数。我现在在控制台中看到了正确的结果,但我不知道如何仅替换匹配段落的内容(使用$(this))。

我在这里做了一个小提琴:http://jsfiddle.net/lharby/x4NRv/

以下代码:

// remove bespoke text and add class 
$qmarkText = $('.post p:contains("+")').each(function() {
    $qStr = $(this).text().slice(1);
    $qmarkText.replaceWith('<p class="subhead-tumblr"' + $qStr + '</p>');
    console.log($qStr); 
});

我知道$ qmarkText并不完全但不确定如何解决这个问题,尝试了几种变体。

希望有人可以帮助我。

1 个答案:

答案 0 :(得分:4)

您可以使用以下代码段:

// remove bespoke text and add class 
$qmarkText = $('p').filter(function () {
    return $(this).text().substring(0, 1) === "+"
}).each(function () {
    $qStr = $(this).text().slice(1);
    $(this).replaceWith('<p class="subhead-tumblr">' + $qStr + '</p>');
});

DEMO

这样可以避免使用匹配偶数字符'+'的:contains()在内容文本中,而不仅仅是在开头。