我正在使用jQuery库Image Picker https://rvera.github.io/image-picker/
我们假设我有相同的设置:
<select class="image-picker" multiple="multiple">
<option data-img-src="http://placekitten.com/220/200" value="1">Cute Kitten 1</option>
<option data-img-src="http://placekitten.com/180/200" value="2">Cute Kitten 2</option>
<option data-img-src="http://placekitten.com/130/200" value="3">Cute Kitten 3</option>
<option data-img-src="http://placekitten.com/270/200" value="4">Cute Kitten 4</option>
</select>
我可以像这样以编程方式选择单个图像
$(".image-picker").val("1");
$(".image-picker").data('picker').sync_picker_with_select();
在这种情况下,将选择第一张图像。如果我选择值为1和4的图像怎么办?我试过了:
$(".image-picker").val(["1","4"]);
$(".image-picker").data('picker').sync_picker_with_select();
但这不起作用。
非常感谢任何帮助。
答案 0 :(得分:3)
确实有效:
$(function() {
$(".image-picker").imagepicker();
$(".image-picker").val(["1", "4"]);
$(".image-picker").data('picker').sync_picker_with_select();
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/image-picker/0.3.0/image-picker.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/image-picker/0.3.0/image-picker.min.css" rel="stylesheet"/>
<select class="image-picker" multiple="multiple">
<option data-img-src="http://placekitten.com/220/200" value="1">Cute Kitten 1</option>
<option data-img-src="http://placekitten.com/180/200" value="2">Cute Kitten 2</option>
<option data-img-src="http://placekitten.com/130/200" value="3">Cute Kitten 3</option>
<option data-img-src="http://placekitten.com/270/200" value="4">Cute Kitten 4</option>
</select>
&#13;
答案 1 :(得分:0)
您想要在选择列表中获取所有图像对象。由于您使用的是自定义data-
元素,因此jQuery选择器有点不稳定:select option[data-img-src]
。然后找出你有多少个图像对象(下面是imgCount
)并在该数组上运行相应长度的for循环:
// 1- Put all img assets into an array using jQuery toArray()
var imgArray = $("select option[data-img-src]").toArray();
// 2- Get number of image assets
var imgCount = imgArray.length;
// 3- Loop through array, limit to number of total objects in array
for (var i=0; i <= imgCount; i++) {
//4- Do whatever you want with imgArray here
}