0

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

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

<-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 来实现这一点

4

3 回答 3

0
    <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>
于 2016-08-01T12:26:41.393 回答
0

你也可以尝试这样的事情:

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('');
}
于 2016-08-01T14:32:31.897 回答
0
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 发表的评论

于 2016-08-01T13:05:54.793 回答