用HTML元素替换文本

时间:2011-07-22 19:20:29

标签: javascript jquery html replace

如何用HTML对象替换特定文本?

示例:

var text = "some text to replace here.... text text text";

var element = $('<img src="image">').event().something...

function ReplaceWithObject(textSource, textToReplace, objectToReplace);

所以我想得到这个:

 "some text to replace < img src...etc >.... text text text"

我想操纵对象元素而不再调用$()方法。

更新 我解决了。

thanx @kasdega,我在你的脚本中创建了一个新脚本,因为在你的脚本中我无法在替换后修改“元素”。 这是脚本:

$(document).ready(function() {
    var text = "some text to replace here.... text text text";
    var element = $('<img />');

    text = text.split('here');
    $('.result').append(text[0],element,text[1]);
$(element).attr('src','http://bit.ly/mtUXZZ');
    $(element).width(100);
});

我不知道append方法接受多个元素。 这就是想法,只需要自动化多次替换

thanx to all,此处为jsfiddle

4 个答案:

答案 0 :(得分:3)

对要替换的文本执行拆分,然后使用数组索引0和1 ...类似于:

function ReplaceWithObject(textSource, textToReplace, objectToReplace) {
    var strings = textSource.split(textToReplace);
    if(strings.length >= 2) {
        return strings[0] + objectToReplace.outerHTML() + strings[1];
    }
    return "";
}

更新:我发现了另一个SO帖子Get selected element's outer HTML,它指向了一个微小的jquery插件,可以帮到这里。

我相信这jsfiddle有你想要的。 outerHTML是我在JSFiddle中包含的微小的jquery插件。

你也可以使用replace来减少一些代码:http://jsfiddle.net/kasdega/MxRma/1/

function ReplaceWithObject(textSource, textToReplace, objectToReplace) {
    return textSource.replace(textToReplace, objectToReplace.outerHTML());
}

答案 1 :(得分:0)

你可以使用$(selector).outerHtml来获取元素的html字符串

答案 2 :(得分:0)

function textToObj (text,obj,$src){
    var className = "placeholder-"+text;
    $src.html($src.html().replace(text,"<div class='"+className+"'></div>"));
    $("."+className).replace(obj);
}

答案 3 :(得分:0)

您可以直接替换html:http://jsfiddle.net/rkw79/qNFKF/

$(selector).html(function(i,o){     return o.replace('old_html','new_html'); })

相关问题