2017-02-25 97 views
1

我有这组输入字段,必须用.confirm中的值替换每个标记。我希望能够在每次点击.btn时替换它。但它只适用于最后一个输入字段。多次用html元素替换单词

Fiddle

HTML

<div class="inputs"> 
    <input class="input-1 anotherclass" type="text"> <br> 
    <input class="input-2 anotherclass" type="text"><br> 
    <input class="input-3 anotherclass" type="text"> <br> 
    <input class="input-4 anotherclass" type="text"> 
</div> 

<div class="confirm"> 
    {input-1} <br> 
    {input-2} <br> 
    {input-3} <br> 
    {input-4} 
</div> 

<button class="btn">edit</button> 

JS

回答

3

的问题是,在each循环的每次迭代,你开始从confirmCopy数据的替换,而不是积累的结果,

这里是一个修正:

var confirmCopy = $(".confirm").data("my-attr", $(".confirm").html()); 
 
$(".btn").on("click", function() { 
 
    var confirm = $(".confirm"); 
 
    var s = confirmCopy.data("my-attr"); 
 
    $("[class*=input-]").each(function(){ 
 
     var inputThis = $(this); 
 
     var className = $.grep(this.className.split(" "), function(v, i){ 
 
      return v.indexOf('input-') === 0; 
 
     }).join(); 
 
     s = s.replace("{"+className+"}", inputThis.val()); 
 
    }); 
 
    confirm.html(s); 
 
    return false; 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div class="inputs"> 
 
    <input class="input-1 anotherclass" type="text"> <br> 
 
    <input class="input-2 anotherclass" type="text"><br> 
 
    <input class="input-3 anotherclass" type="text"> <br> 
 
    <input class="input-4 anotherclass" type="text"> 
 
</div> 
 

 
<div class="confirm"> 
 
    {input-1} <br> 
 
    {input-2} <br> 
 
    {input-3} <br> 
 
    {input-4} 
 
</div> 
 

 
<button class="btn">edit</button>

0

问题是在这里

confirm.html(confirmCopy.data("my-attr").replace("{"+className+"}", inputThis.val())); 

您正在使用相同的旧模板更新股利。 confirmCopy.data("my-attr")

每次更换后,你应该更新变种confirmCopy

这将工作完美。

$(文件)。就绪(函数(){VAR confirmCopy = $()的数据( “我的-ATTR ”$()HTML())“ 进行确认。” “确认”。

$(".btn").on("click", function() { 
    var confirm = $(".confirm"); 
    var temp = confirmCopy.data("my-attr"); 
    $("[class*=input-]").each(function(){ 
    var inputThis = $(this); 


    var className = $.grep(this.className.split(" "), function(v, i){ 
    return v.indexOf('input-') === 0; 
     }).join(); 

    temp = temp.replace("{"+className+"}", inputThis.val()); 

    confirm.html(temp); 

    }); 
}); 
}); 
+0

呵呵?如果你这样做了{{}'占位符将会丢失 – charlietfl

+0

尝试运行这个。 btw哪些占位符? –

+0

存储在$(“。confirm”)。data(“my-attr”)中的占位符。你正在删除他们 – charlietfl