我想在单击特定图像时自动选择下拉列表中的选项,我已经制作了一个JsFiddle来显示我当前的代码,是否有人能指出我正确的方向?
HTML:
<img class="auto-image" data-name="01" style="cursor:pointer;" src="img/Plaque/Horses/01.png">
<select name="productOption[]" id="product-option-11" class="product-option product-option-select" data-force="0" data-title="Image">
<option value="0" data-price="0">Please select...</option>
<option value="11::167" data-price="0.0000" data-modify="0">01</option>
</select>
JS:
$('.auto-image').on('click', function() {
var search = $(this).data('name');
console.log('Click is being run, search has been varred as: ' + search);
$('.product-option-select').find('option[text=' + search + ']').attr('selected', 'selected');
var found = $('.product-option-select').find('option[text=' + search + ']').val();
console.log('Oh, and I found the option, value is: ' + found);
});
控制台显示此时:
Click is being run, search has been varred as: 01
Oh, and I found the option, value is: undefined
干杯
答案 0 :(得分:1)
使用此 Demo Fiddle
$('.product-option-select').find('option:contains(' + search + ')')
find('option[text=' + search + ']')
是一个错误的选择器。使用 :contains() 完整的JS代码修改:
$('.auto-image').on('click', function() {
var search = $(this).data('name');
console.log('Click is being run, search has been varred as: ' + search);
$('.product-option-select').find('option:contains(' + search + ')').attr('selected', 'selected');
var found = $('.product-option-select').find('option:contains(' + search + ')').val();
console.log('Oh, and I found the option, value is: ' + found);
});
替代:contains()
,
$(".product-option-select option").filter(function () {
return $.trim($(this).text()) == search;
}).attr('selected', 'selected');