无法使用'in'运算符来搜索错误

时间:2016-01-14 00:57:20

标签: javascript jquery

假设我正在创建一个用户可以上传多张照片的应用,但他们可以上传一张照片一次。我想附加一个背景图像,并获取file_name值来设置输入的值。我在下面写了algorithim,但它有错误,不能使用'in'运算符来搜索..

这是js

$.each('#photo_area div', function(i, obj) {
  i++;
  if (!obj.attr('style')) {
    obj.attr('style', 'background:url(' + data.result.filename + ') no-repeat center center');
    $('input[name="photos' + i + '"]').val(data.result.filename);

    return false;
  }
});

这是我的DOM

<div></div>
<div></div>
<input type="hidden" name="photo1">
<input type="hidden" name="photo2">

2 个答案:

答案 0 :(得分:3)

您未正确调用$.each$.each的第一个参数必须是数组或对象,而不是字符串。要迭代jquery集合,请使用.each()方法,而不是$.each.

在迭代函数中,obj是一个DOM元素,而不是一个jQuery对象。要使用jQuery方法,您必须使用$(obj)$(this)

$("#photo_area div").each(function(i, obj) {
  i++;
  if (!$(obj).attr('style')) {
    $(obj).attr('style', 'background:url(' + data.result.filename + ') no-repeat center center');
    $('input[name="photos' + i + '"]').val(data.result.filename);

    return false;
  }
});

从迭代函数返回false会停止循环。那是你要的吗?因此,这只会更新没有style属性的第一个匹配DIV。

答案 1 :(得分:0)

$("#photo_area div").each(function(i, obj) {
 i++;
 if (!$(obj).attr('style')) { // edited part
$(obj).attr('style', 'background:url(' +              data.result.filename + ') no-repeat center center');
$('input[name="photos' + i +             '"]').val(data.result.filename);

return false;

} });

使用$(obj)代替'obj'