查找属性title是否与所选选项值-jquery匹配



我有一个场景,我想在div中找到所选选项的值作为图像标题,并向其添加类

选择:

<table class="variations" cellspacing="0">
<tbody>
<tr>
<td class="label"><label for="pa_color">Color</label></td>
<td class="value">
<select>
<option value="">Izberi možnost</option>
<option value="first" class="attached enabled">first</option>
<option value="second" class="attached enabled">second</option>
</select>

</td>
</tr>
</tbody>
</table>

并检查图像标题中所选选项的值,并添加类别:

<div class="woocommerce-product-gallery__image">
<a href="#">
<img title="first"  http://localhost:8080/img.jpg >
</a>
<a href="#">
<img title="second"  http://localhost:8080/img2.jpg >
</a>
jQuery(document).ready(function($){ 
var activeSlide = $('.woocommerce-product-gallery__image.flex-active-slide');
var pictureTitle = $(".woocommerce-product-gallery__image a img").attr('title');
var picture = $(".woocommerce-product-gallery__image a img");
$(".variations select").change(function(){ 
var optionValue = $(this).children("option:selected").val();

if (pictureTitle === optionValue) {
//find image with selected title in list of images and add class to that image
}   
});
});

感谢您的帮助,

jQuery(document).ready(function($) {
$(".variations select").change(function() {
var optionValue = $(this).val(); // get the value of select which is basically the value of selected option.
let img = $(".woocommerce-product-gallery__image a img[title='" + optionValue + "']"); // A selector to select the img with the selected. title
img.addClass("selected");
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="variations" cellspacing="0">
<tbody>
<tr>
<td class="label"><label for="pa_color">Color</label></td>
<td class="value">
<select>
<option value="">Izberi možnost</option>
<option value="first" class="attached enabled">first</option>
<option value="second" class="attached enabled">second</option>
</select>
</td>
</tr>
</tbody>
</table>
<div class="woocommerce-product-gallery__image">
<a href="#">
<img title="first" http://localhost:8080/img.jpg>
</a>
<a href="#">
<img title="second" http://localhost:8080/img2.jpg>
</a>

这应该能完成你的工作。

最新更新