使用输入字段自定义文本

Customize text with input fields

有谁知道单击复选框时我将如何修复重复项?

<label><input type="checkbox" data-bValue="100" data-sValue="sV1" data-nValue="nV1" name="layers"> 100</label><label><input type="checkbox" data-bValue="200" data-sValue="sV2" data-nValue="nV2" name="layers"> 200</label><label><input type="checkbox" data-bValue="300" data-sValue="sV3" data-nValue="nV3" name="layers"> 300</label><label><input type="checkbox" data-bValue="400" data-sValue="sV4" data-nValue="nV4" name="layers"> 400</label><label><input type="checkbox" data-bValue="500" data-sValue="sV5" data-nValue="nV5" name="layers"> 500</label><label><input type="checkbox" data-bValue="600" data-sValue="sV6" data-nValue="nV6" name="layers"> 600</label><label><input type="checkbox" data-bValue="700" data-sValue="sV7" data-nValue="nV7" name="layers"> 700</label><h1 id="render"></h1>

我的搜索让我相信我必须重新做这一切,但我想我先在这里问。

Fiddle: https://jsfiddle.net/swedoc/Lwr16wrt/

    $(document).ready(function() {

    var scents = [];
    var notes = [];
    var theRender = document.getElementById("render"); 

    $("input[name='layers']").on('click', function(){ 

                $.each($("input[name='layers']:checked"), function(){            
                    scents.push($(this).attr("data-sValue"));
                });        

                $.each($("input[name='layers']:checked"), function(){            
                    notes.push($(this).attr("data-nValue"));
                });

                    theRender.innerHTML 
                    += "You’ve created a<br>" 
                    + scents.join(', ').replace(/,(?!.*,)/gmi, ' and') + " sValue with " 
                    + notes.join(', ').replace(/,(?!.*,)/gmi, ' and') + " nValue.";                        
    });
});

答案都是关于变量的范围。您需要在函数内部而不是外部声明数组。

同时删除 innerHTML += 中的“+”。

$("input[name='layers']").on('click', function(){ 
    var scents = [];
    var notes = []; 

    $.each($("input[name='layers']:checked"), function(){            
        scents.push($(this).attr("data-sValue"));
    });        

    $.each($("input[name='layers']:checked"), function(){            
        notes.push($(this).attr("data-nValue"));
    });

    theRender.innerHTML = "You’ve created a<br>" 
      + scents.join(', ').replace(/,(?!.*,)/gmi, ' and') + " sValue with " 
      + notes.join(', ').replace(/,(?!.*,)/gmi, ' and') + " nValue.";                        
});

这是您更正的 fiddleJs:https://jsfiddle.net/Lwr16wrt/23/