用HTML元素替换文本 [英] Replace text with HTML element

查看:121
本文介绍了用HTML元素替换文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How can I replace a specific text with HTML objects?

示例:

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"

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

And I would like manipulate the object element without call again $() method.

UPDATE:
我解决了。

UPDATE: I solved.

thanx @kasdega,我根据你的脚本制作了一个新脚本,因为在你的脚本中我无法修改替换后的元素。
这是脚本:

thanx @kasdega, i made a new script based in your script, because in your script i can't modify the "element" after replace. This is the script:

$(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方法接受多个元素。
这就是想法,只需要自动执行多次替换

I didnt know that append method accept multiples elements. That is the idea, only need to automate for multiple replacements

thanx to all,这里 jsfiddle

thanx to all, and here the jsfiddle

推荐答案

对你想要的文字进行拆分替换然后使用数组索引0和1 ...类似于:

do a split on the text you want to replace then use the array indexes 0 and 1...something like:

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

更新:我发现另一个SO帖子获取所选元素的外部HTML ,它指向了一个微小的jquery插件,可以帮到这里。

UPDATE: I found another SO post Get selected element's outer HTML that pointed me to a tiny jquery plugin that helps here.

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

I believe this jsfiddle has what you want. outerHTML is the tiny jquery plugin I included in the JSFiddle.

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

You can also use replace which will reduce some code: http://jsfiddle.net/kasdega/MxRma/1/

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

这篇关于用HTML元素替换文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆