迭代并同时替换span

时间:2013-05-24 03:07:56

标签: javascript jquery

假设我有以下代码迭代<span>内的<div>

$('#recommendTextArea').children('span').each(function () {
    //mentionedFriends.push($(this).html()); 
    var mentionedFriendName = $(this).html();
    jQuery.each(friendsList, function () {
        if (this.name == mentionedFriendName) {
            var facebookId = '@[' + this.id + ']';
        }
    });
});

我基本上想用<span>字符串替换此facebookId。这样的事可能吗?如果是的话怎么样?

1 个答案:

答案 0 :(得分:3)

使用replaceWith

$('#recommendTextArea').children('span').each(function () {
    var $span = $(this);

    //mentionedFriends.push($(this).html()); 
    var mentionedFriendName = $(this).html();
    jQuery.each(friendsList, function () {
        if (this.name == mentionedFriendName) {
            var facebookId = '@[' + this.id + ']';
            $span.replaceWith(facebookId);
        }
    });
});

编辑:如果你需要处理特殊字符等,你可以这样做:

$span.replaceWith($("<div>").text(facebookId).contents());
相关问题