首页 > 解决方案 > 查找属性标题是否与选定的选项值匹配 - 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

解决方案


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>

这应该可以完成您的工作。


推荐阅读