用Json值替换JavaScript中的图释文本

时间:2017-05-08 21:44:42

标签: javascript jquery json

我正在尝试用图像替换文本。例如,abc :)应该转换为abc(和相应的表情符号)。我使用contenteditable元素做同样的事情。但是,似乎什么都没有用。我试过使用replace()和html()函数但它们不起作用。

指向我的Codepen的链接是:Link

我不想使用正则表达式,因为我必须在我的json文件中添加更多内容。谢谢!

HTML代码:

<div contenteditable="true" id='text-box'>  
</div>

JS代码:

document.body.onkeyup=function(e){
            if(e.keyCode==32){
                var contenteditable = document.querySelector('[contenteditable]'),
                text = contenteditable.textContent;
                var word=getWord(text);
                console.log(word);
                console.log(data.value);
                if(word.includes(data.value)){
                    //alert("true");
                    var img=new Image();
                    img.src=data.image;
                    img.setAttribute("class","image");
                    //$("#text-box").append(img);
                    $("#text-box").html(function (_, html) {
     return html.replace(data.value , img );

                }       
                //$("#text-box").html(text.replace(data.value,img));
            }
        }

        function getWord(text){
            var word=text.split(" ").pop();
            return word;
        }

JSON数据:

var data={
    "value":":)",
    "image":"persons-0016_large.png"
};

执行我的代码后,我得到的输出为abc[object HTMLImageElement],而不是图像本身。

1 个答案:

答案 0 :(得分:1)

不是创建图像对象,而是像这样用图像标记替换文本。

var data={
    "value":":)",
    "image":"persons-0016_large.png"
};


document.body.onkeyup=function(e){
    if(e.keyCode==32){
        var contenteditable = document.querySelector('[contenteditable]');
        var text = contenteditable.textContent;
        var word=getWord(text);
        console.log(word);
        console.log(data.value);
        if(word.includes(data.value)){
            //alert("true");
            //var img=new Image();
            //img.src=data.image;
            //img.setAttribute("class","image");

            var img = "<img src='" + img.src +"' class='image' /> ";
            //$("#text-box").append(img);
            $("#text-box").html(function (_, html) {
                return html.replace(data.value , img );
            } );      
        //$("#text-box").html(text.replace(data.value,img));
        }
    };

};

function getWord(text){
    var word=text.split(" ").pop();
    return word;
}