我对jQuery很陌生,我的代码正在发生一些奇怪的事情。jQuery总是返回相同的数字,即使我按不同的图像。问题出在哪里?
HTML代码
$(".image-upload").on("change", function() {
console.log($(this).children("label").find("img").attr("data-id"));
});<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-md-2">
<div class="image-upload">
<label for="file-input">
<img src="<?= base_url("upload.png"); ?>" width="100" height="100" data-id="1"/>
</label>
<input name="photos[]" id="file-input" type="file" data-ids="1" />
</div>
</div>
<div class="col-md-2">
<div class="image-upload">
<label for="file-input">
<img src="<?= base_url("upload.png"); ?>" width="100" height="100" data-id="2"/>
</label>
<input name="photos[]" id="file-input" type="file" data-ids="2" />
</div>
</div>
当启动更改时,控制台显示1,无论按哪个img。为什么?
发布于 2017-11-08 19:49:31
好像是这样写的:
$(this).children("label").children("img").attr("data-id")将输出正确的数据id。注意“子”而不是“查找”的用法。
此外,通常更好的做法是提供某种类型的在线示例,这样可以更容易地运行和测试问题。https://jsfiddle.net/947f2hhf/
发布于 2017-11-08 19:54:16
<div class="col-md-2">
<div class="image-upload">
<label for="file-input">
<img src="<?= base_url("upload.png"); ?>" width="100" height="100" data-id="1"/>
</label>
<input name="photos[]" id="file-input" type="file" data-ids="1"/>
</div>
</div>
<div class="col-md-2">
<div class="image-upload">
<label for="file-input">
<img src="<?= base_url("upload.png"); ?>" width="100" height="100" data-id="2"/>
</label>
<input name="photos[]" id="file-input2" type="file" data-ids="2" />
</div>
</div>html标记id必须是唯一的。必须更改第二个文件-输入标签‘id’。
https://stackoverflow.com/questions/47188247
复制相似问题