单击两次重新插入循环元素

时间:2015-06-02 13:33:18

标签: javascript jquery loops concatenation

我的代码,点击"产生",从文本区域中取词,循环,并以我需要的方式连接。 一切顺利,一切正常。

但是

如果我按"清除"然后点击"生成"再次,我的代码插入两次循环的单词。

问题:每次点击"生成"我怎样才能始终得到相同的结果?

jsfiddle

HTML:

<textarea id="KWarea" rows="4" cols="50">*casio*
    *citizen*
    *clarks*
    </textarea>
<br>
<button id="produce">produce</button>
<button id="clear">clear</button>
<br />
<br />
<div id="result"></div>
<br />
<br />
<br />
<div id="result">
    Expected result example:
        <br />
    ("*casio*","* casio *", "*citizen*", "* citizen *", "*clarks*", "* clarks *")
</div>

jQuery的:

$(document).ready(function () {
    var endString = "";
    $('#produce').click(function () {
        var myTxtArea = document.getElementById('KWarea');
        myTxtArea.value = myTxtArea.value.replace(/^\s*|\s*$/g, '');

        var lines = $('#KWarea').val().replace(/\*/g, '').split('\n');
        for (var i = 0; i < lines.length; ++i) {
            endString += '"*' + lines[i] + '*"' + ',' + '"* ' + lines[i] + ' *"' + ',';
          //   console.log(lines[i]);
        }
        var trimmedStr = endString.slice(0, -1);
        $('#result').html("Here is the final string:( " + trimmedStr + ")");

    });

    $('#clear').click(function () {
        $('#result').empty();
    });

});

2 个答案:

答案 0 :(得分:1)

您正在追加字符串而不先清空它,请尝试:

$(document).ready(function () {
    var endString = "";
    $('#produce').click(function () {
        var myTxtArea = document.getElementById('KWarea');
        myTxtArea.value = myTxtArea.value.replace(/^\s*|\s*$/g, '');

        var lines = $('#KWarea').val().replace(/\*/g, '').split('\n');
        endString ='';
        for (var i = 0; i < lines.length; ++i) {
            endString += '"*' + lines[i] + '*"' + ',' + '"* ' + lines[i] + ' *"' + ',';
          //   console.log(lines[i]);
        }
        var trimmedStr = endString.slice(0, -1);
        $('#result').html("Here is the final string:( " + trimmedStr + ")");

    });

    $('#clear').click(function () {
        $('#result').empty();
    });

});

答案 1 :(得分:1)

发生这种情况的原因是因为您将endString作为全局变量。解决这个问题 var endString = "";$('#produce').click(function () {

喜欢这样

$(document).ready(function () {

    $('#produce').click(function () {
            var endString = "";
        var myTxtArea = document.getElementById('KWarea');
        myTxtArea.value = myTxtArea.value.replace(/^\s*|\s*$/g, '');

        var lines = $('#KWarea').val().replace(/\*/g, '').split('\n');
        for (var i = 0; i < lines.length; ++i) {
            endString += '"*' + lines[i] + '*"' + ',' + '"* ' + lines[i] + ' *"' + ',';
          //   console.log(lines[i]);
        }
        var trimmedStr = endString.slice(0, -1);
        $('#result').html("Here is the final string:( " + trimmedStr + ")");

    });

    $('#clear').click(function () {
        $('#result').empty();
    });

});