【问题标题】:Replace String to html content using javascript使用 javascript 将字符串替换为 html 内容
【发布时间】:2016-08-01 12:18:08
【问题描述】:

我有这个来自 JSON 的字符串渲染“我是 1 美元的前端开发人员,从 3 美元开始以 2 美元的价格工作”。

现在,我想用动态 html 输入文本框替换 $1$,$2$$3$。所以,输出应该是 I am

<-input textbox here> frontend developer works at <-input textbox here> from <-input textbox here>.

var str = "I am $1$ frontend developer works at $2$ from $3$";
var newStr = "";
for(var i=0;i<3;i++){
var id = '$'+i+'$';
if (str.indexOf(id) >= 0){
   newStr = str.replace(id, $.parseHTML('<div><input type="text" 
id="input-"+i/></div>'));
}

我尝试使用字符串替换方法。但它似乎只适用于字符串。我可以使用任何其他方法来使用 javascript/jquery 实现此目的

【问题讨论】:

  • 您可以发布您尝试过的任何代码吗?
  • 你能展示一下,你的尝试是什么?
  • 如果你想要用复选框替换那些 $number$ 试试这个"I am $1$ frontend developer works at $2$ from $3$".replace(/\$\d\$/g, '&lt;input type=checkbox /&gt;')
  • 这将替换它们并添加 idjsfiddle.net/yao5zmgk

标签: javascript jquery dynamic-html


【解决方案1】:
    <div id="div1">
    </div>

    <script type="text/javascript">
var data = "I am $1$ frontend developer works at $2$ from $3$";
     //include jQuery before this code
      $(function(){
        data.replace('$1$','<input type="text" />').replace('$2$','<input type="text" />').replace('$3$','<input type="text" />');
       });

   $('#div1').html(data);
    </script>

【讨论】:

    【解决方案2】:
    var input = "I am $1$ frontend developer works at $2$ from $3$";
    var result = input.replace(/\$\d\$/g, '<div><input type="text" id="input-"+i/></div>');
    

    现在的结果是:

    I am <div><input type="text" id="input-"+i/></div> frontend developer works at <div><input type="text" id="input-"+i/></div> from <div><input type="text" id="input-"+i/></div>
    

    我使用的正则表达式来自@n0m4d 发表的评论

    【讨论】:

      【解决方案3】:

      你也可以试试这样的:

      var input = "I am $1$ frontend developer works at $2$ from $3$";
      var result = replaceWithInputTags(input, '$')
      
      function replaceWithInputTags(source, templateChar){
         var sourceArgs = source.split(templateChar);
      
         return sourceArgs.map(function(item){
             var index = +item;
             if (isNaN(index)) return item;
             return "<input type='text' id='input-" + (index-1) + "' />";       
         }).join('');
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-11-26
        • 1970-01-01
        • 2022-11-14
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多