Javascript 设置用户每次上传的图像背景

Javascript 设置用户每次上传的图像背景,javascript,jquery,Javascript,Jquery,想象一下,我试图做到这一点: 用户将看到完成上传的照片的结果,如果第一个图像存在,则附加到第二个块,依此类推。但我下面的代码有缺陷,它在所有div上都附加了一张照片。我的逻辑怎么了 $("#photo_area div").each(function(i, obj) { i++; var stopLoop = false; if (!$(obj).attr('style') && stopLoop == false) { $(obj).attr('style'

想象一下,我试图做到这一点:

用户将看到完成上传的照片的结果,如果第一个图像存在,则附加到第二个块,依此类推。但我下面的代码有缺陷,它在所有
div
上都附加了一张照片。我的逻辑怎么了

$("#photo_area div").each(function(i, obj) {
  i++;
  var stopLoop = false;
  if (!$(obj).attr('style') && stopLoop == false) {
    $(obj).attr('style', 'background:url(http://example.com/' + encodeURI(data.file_name) + ') no-repeat center center');
    $('input[name="photos' + i + '"]').val(encodeURI(data.file_name));
    stopLoop = true;
  }
});
我的DOM

<div id="photo_area">
            <div></div>
            <div></div>
            <div></div>
            <div></div>
            <input type="hidden" name="photo1">
            <input type="hidden" name="photo2">
            <input type="hidden" name="photo3">
            <input type="hidden" name="photo4">
        </div>


我创建了一个示例,使用颜色作为示例:

如果您想在列表上的图像未上载时停止循环,可以通过为
If
条件编写
else
语句并移动
stopLoop=true
else
语句并移动
var stopLoop=false在循环之外。否则,就不能使用
stopLoop
变量。

您觉得这个变量怎么样? 只是做了所有的事

$。each()
函数。当迭代时有一个空div时,在运行中创建

PS:为了简化示例,使用了JSFIDLE徽标图像

结果:

<div id="photo_area">
    <div style="background:url(https://jsfiddle.net/img/logo.png) no-repeat center center"><input type="hidden" name="photos1" value="https://jsfiddle.net/img/logo.png"></div>
    <div style="background:url(https://jsfiddle.net/img/logo.png) no-repeat center center"><input type="hidden" name="photos2" value="https://jsfiddle.net/img/logo.png"></div>
    <div style="background:url(https://jsfiddle.net/img/logo.png) no-repeat center center"><input type="hidden" name="photos3" value="https://jsfiddle.net/img/logo.png"></div>
    <div style="background:url(https://jsfiddle.net/img/logo.png) no-repeat center center"><input type="hidden" name="photos4" value="https://jsfiddle.net/img/logo.png"></div>
</div>

检查此项 这就是你要找的吗

使用以下选择器:

$("#photo_area div:not([style]):first")
它首先选择所有没有样式属性的div,然后从该列表中选择第一个div

编辑: 参考
了解如何在隐藏字段中放置相同的值。我使用了小提琴中的普通文本框来查看更新的值。

您介意为我们提供JSFIDLE吗?它将帮助我们,看看它。@JeremyRajan@Jennifer,所以,我似乎不太理解你的要求:-)要改进,你可以在移动中创建更多的