我试图根据特定输入字段的值将图像'x'次数添加到div中。随着数量的增加或减少,我需要图像出现/消失。想想我的路要走这一点,但这里是我在哪里:jquery基于输入字段将图像添加到div
for(i=0; i<cans; i++) {
$('.cans').append('<img src="can.png" />');
}
其中” .cans'显然是在div容器,‘罐’是VAR设置为输入字段的值。 任何和所有的帮助总是非常感激!
我试图根据特定输入字段的值将图像'x'次数添加到div中。随着数量的增加或减少,我需要图像出现/消失。想想我的路要走这一点,但这里是我在哪里:jquery基于输入字段将图像添加到div
for(i=0; i<cans; i++) {
$('.cans').append('<img src="can.png" />');
}
其中” .cans'显然是在div容器,‘罐’是VAR设置为输入字段的值。 任何和所有的帮助总是非常感激!
这样的事情应该工作,特别是如果你输入的是一个选择。如果它实际上是一个文本输入,你也需要做一个事件监听器。
$('input_field_id').change(function(){
$('.cans').html('');
var cans = parseInt($(this).val());
for(i=0; i<cans; i++) {
$('.cans').append('<img src="can.png" />');
}
})
HTML:
<input type="text"/>
<div class="cans"></div>
的jQuery:
$('input[type=text]').on('change',function(){
$('.cans').empty(); //Remove all child nodes
var value = $(this).val();
for(i=0; i<parseInt(value); i++) {
$('.cans').append('<img src="can.png" />');
}
});
退房JSFiddle。
$('.cans').empty(); //Remove all child nodes
所以不需要递减
@ DJDavid98谢谢:)您指出的错误。更新。 – Praveen
$('input').on('change keydown',function(){ //add a change listener
var count = parseInt($(this).val()); //store the value in a variable as a number
if (!isNaN(count)){ //check if the value is actually a numer
$('.cans').html(''); //clear previous images from the element
for (var i=0; i<count; i++) $('.cans').append('<img src="can.png" />');
}
})
感谢您的所有快速回复。这看起来像所有我需要的只是意味着清除.cans块中的html到我的代码。我实际上使用的是输入范围滑块,初始测试显示它工作正常。 – jmarx34