gpt4 book ai didi

javascript - 用 HTML 元素替换文本

转载 作者:太空狗 更新时间:2023-10-29 16:09:00 27 4
gpt4 key购买 nike

如何用 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"

我想在不再次调用 $() 方法的情况下操作对象元素。

更新:我解决了。

谢谢@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 方法接受多个元素。就是这个思路,只需要自动化进行多次替换

感谢所有人,这里是 jsfiddle

最佳答案

对要替换的文本进行拆分,然后使用数组索引 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());
}

关于javascript - 用 HTML 元素替换文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6794984/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com