克隆元素基于动态值创建无限循环

时间:2017-11-06 20:11:08

标签: javascript jquery clone onchange

我有一个滑块输入字段,在滑动时给出一个数值。我想基于滑块值克隆对象X次,但是当我尝试完成此操作时,它会创建一个无限循环。无论如何,当克隆元素发生变化时,它的数量是否与滑块值相匹配?这是我正在使用的代码。

jQuery(document).ready(function($) {
$(window).load(function() {

$('input#fieldname3_1').change(function() {

var e = $('#student-icons.icon > span');
var n = $('#fieldname9_1').val();

$('#student-icons.icon').html(
    for (var i = 0; i < n; i++) {
      e.clone().insertAfter(e);
});
}).change()
});
});

1 个答案:

答案 0 :(得分:0)

尝试以下设置:

HTML:

<input type="range" id='fieldname3_1' style='width: 200px'>

<div id='student-icons' class='icon'></div>

JavaScript的:

$(document).ready(function($) {
        $('input#fieldname3_1').change(function() {
            var n = $(this).val();

            // reset the element
            $('#student-icons.icon').html('');
            for (var i = 0; i < n; i++) {
                // The html of what you want to clone goes here
                $('#student-icons.icon').append("<div id='hello'>"+i+"</div>")
            }
        });
});

如果浏览器支持不是问题,我还建议使用oninput事件(仅限IE 9及以上版本):

$(document).ready(function($) {
        $('input#fieldname3_1')[0].oninput = function() {
            var n = $(this).val();

            $('#student-icons.icon').html('');
            for (var i = 0; i < n; i++) {
                $('#student-icons.icon').append("<div id='hello'>"+i+"</div>")
            }
        };
});

这将允许事件在输入改变后立即触发,而不是等待keydown。

JsFiddle
JsFiddle w/ onInput

相关问题