【问题标题】:Replace text with HTML element用 HTML 元素替换文本
【发布时间】:2011-10-11 07:40:26
【问题描述】:

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

感谢所有人,这里是jsfiddle

【问题讨论】:

    标签: javascript jquery html replace


    【解决方案1】:

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

    【讨论】:

    • 好的。我这样做: var obj = $(''); '一些字符串 2 替换'.replace('string',$(obj).outerHTML);但是当我尝试这样做时 $(obj).click(function(){console.log('works!');});不工作。
    【解决方案2】:

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

    【讨论】:

      【解决方案3】:
      function textToObj (text,obj,$src){
          var className = "placeholder-"+text;
          $src.html($src.html().replace(text,"<div class='"+className+"'></div>"));
          $("."+className).replace(obj);
      }
      

      【讨论】:

        【解决方案4】:

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

        $(选择器).html(函数(i,o) { 返回 o.replace('old_html','new_html'); })

        【讨论】:

        • 这没有回答问题:“用 HTML 元素替换 text
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多