jQuery找到值然后替换SRC

时间:2010-12-22 10:41:28

标签: jquery replace

任何人都可以看到这个代码有什么问题,它只是不起作用......

我想:

获取#product-variants-option-0

的值

搜索#preload以获取相关图片和

然后将div.image img src更改为该图像

jQuery(document).ready(function($) {
   $('#product-variants-option-0').change(function() {

     // What is the sku of the current variant selection.
     var select_value = $(this).find(':selected').val();

            if (select_value == "Kelly Green") {
             var keyword = "kly";
            };

        var new_src = $('#preload img[src*=keyword]');

        $('div.image img').attr('src', new_src);

   });
 });

选择:

<select class="single-option-selector-0" id="product-variants-option-0">
<option value="Kelly Green">Kelly Green</option>
<option value="Navy">Navy</option>
<option value="Olive">Olive</option>
<option value="Cocoa">Cocoa</option>
</select>

我正在尝试搜索无序列表:

<ul id="preload" style="display:none;">
<li><img src="0z-kelly-green-medium.jpg"/></li>
<li><img src="0z-olive-medium.jpg"/></li>
</ul>

我想要替换的图像是:

2 个答案:

答案 0 :(得分:1)

我看到一些问题:

  1. 你不是将“Kelly Green”改为“kelly”。
  2. var new_src = $('#preload img[src*=keyword]');已将keyword硬编码到其中(不是关键字变量的值)。
  3. 列表中的li s里面没有img个元素(它们只是直接包含URL作为文本)。 您已编辑过问题并解决了这个问题。
  4. 如果选择的值不是“Kelly Green”,那么你不会将它设为小写,而你根本就没有使用该值。
  5. 您没有检索预加载图片的src属性。
  6. 如果您将列表更改为:

    <ul id="preload" style="display:none;">
    <li><img src='0z-kelly-green-medium.jpg'></li>
    <li><img src='0z-olive-medium.jpg'></li>
    </ul>
    

    (这是修复过的部分。)

    然后这应该有效:

    jQuery(document).ready(function($) {
       $('#product-variants-option-0').change(function() {
         var select_value, keyword, new_src;
    
         // What is the sku of the current variant selection
         select_value = $(this).find(':selected').val();
    
         // Get the keyword to use (the value in lower case, or "kelly" if the
         // value is "Kelly Green")
         keyword = select_value == "Kelly Green" ? "kelly" : select_value.toLowerCase();    
    
         // Find the image using that `src`, note that we concatenate the value
         // from `keyword`, rather than having it in a literal.
         new_src = $('#preload img[src*=' + keyword + ']').attr('src');
    
         // Set the image's source.
         $('div.image img').attr('src', new_src);
       });
    });
    

    Live example


    查尔斯,你要求提供关于如何以不同方式编写文字的意见,我说我有一分钟要做些什么。对不起,我的真正的工作需要我一会儿。

    我可能会这样做,假设你在应用程序的其他地方有这种选择框,因此概括是值得的。

    1. 尽可能让事情可以重复使用(好吧,差不多;我把剩下的一些概括作为练习留给读者)。
    2. 不要将图片网址存储在一个地方,将选项存储在另一个地方;把它们放在一起,这样它们都可以很容易地来自同一个数据源。这减少了错误。 (例如,在您的问题中,您有四个选项,但在预加载结构中只有两个选项的图像。现在,如果您没有其他图像,那很好,请保留属性或使其成为空白,但保持在一起/从同一来源生成是一个好主意。)
    3. 使用data-image属性执行#2,该属性从HTML5开始有效,在早期版本中完全无害。 (Details
    4. 不要在HTML中包含预加载的标记;生成它。这与#2有关,也与没有JavaScript的用户不需要预先存储的图像有关,因为它们不会被使用。所以不要把他们不需要的东西推到他们身边。
    5. HTML:

      <select class="single-option-selector-0" id="product-variants-option-0">
      <option
        value="Kelly Green"
        data-image="0z-kelly-green-medium.jpg"
        >Kelly Green</option>
      <option
        value="Navy"
        data-image="0z-navy-medium.jpg"
        >Navy</option>
      <option
        value="Olive"
        data-image="0z-olive-medium.jpg"
        >Olive</option>
      <option
        value="Cocoa"
        data-image="0z-cocoa-medium.jpg"
        >Cocoa</option>
      </select>
      

      <div class='image'><img src='placeholder.jpg'></div>
      

      JavaScript with jQuery:

      (function($) {
        // A utility function from my arsenal; you can
        // just inline this if you don't want it.
        // Returns an array containing the given attribute
        // from *all* of the elements in the jQuery object.
        // Args:
        //  name        Name of the attribute to fetch
        //  blanksOkay  (Optional, default false) true if
        //              you want blanks in the array for
        //              blank entries or non-existant entries;
        //              false if you want them left out.
        $.fn.attrAll = function(name, blanksOkay) {
          var list, index;
      
          if (typeof blanksOkay === "undefined") {
            blanksOkay = false;
          }
      
          list = [];
          for (index = 0; index < this.length; ++index) {
            entry = $(this[index]).attr(name);
            if (entry || blanksOkay) {
              list.push(entry);
            }
          }
          return list;
        };
      
      })(jQuery);
      
      // The page's ready script
      jQuery(function($) {
      
        // Set up the product variants select box.
        // You could generalize this with classes or other attributes
        // (so there would be *nothing* special about the select box),
        // but I didn't want to change your markup too much.
        setupSelectWithImages(
          '#product-variants-option-0',
          'div.image img:first'
        );
      
        // ===
        // All of the following would probably be in your
        // utility script; it's not page-specific.
        // ===
      
        // Set up our select box that's equipped with images
        // so it shows the image when an option is selected.
        // The options within the box should have data-image
        // attributes for their images, which are precached.
        // Args:
        //   boxSelector     The selector that finds the select box
        //   targetSelector  The selector that finds the target img
        function setupSelectWithImages(boxSelector, targetSelector) {
          var box;
      
          // Get the select box
          box = $(boxSelector);
      
          // Preload the images
          preloadImages(box.find('option'), 'data-image');
      
          // Ensure we show the correct image when the select box
          // changes, and force showing it right now for the default
          // value.
          setCurrentImage.call(box[0]);
          box.change(setCurrentImage);
          function setCurrentImage() {
            var entry = $(this).find('option:selected').attr('data-image');
            if (entry) {
              display("Setting src to " + entry);
              $(targetSelector).attr('src', entry);
            }
          }
      
          // Done with box
          box = undefined;
        }
      
        // Another general purpose function; preloads the images
        // defined by the given attribute on the elements in the
        // given jQuery object.
        // I've kept things bundled up (in a div rather than a ul),
        // but there's no special reason to, you could just add
        // the individual images to the body directly.
        // Using a container makes it easy to return a single
        // thing out of this function, which may be useful
        // to some calling code.
        function preloadImages(list, attrName) {
          var markup;
      
          // Get a list of the relevant attribute
          markup = list.attrAll('data-image');
      
          // Convert it into a bunch of img tags
          markup = joinEntries(markup, "<img src='", "'>");
      
          // Put them in an off-page div, add it to the document,
          // and return the div to the caller
          return $("<div/>").css({
            'position': 'absolute',
            'left': '-10000px',
            'top': '0px'
          }).html(markup).appendTo(document.body);
        }
      
        // Join the entries in the array with the given
        // prefix and suffix.
        function joinEntries(a, prefix, suffix) {
          prefix = prefix || '';
          suffix = suffix || '';
          return prefix + a.join(suffix + prefix) + suffix;
        }
      
        // This is just for our purposes in this demo
        function display(msg) {
          $("<p/>").html(msg).appendTo(document.body);
        }
      });​
      

      Live example(但实际示例使用了一些gravatars,因此您实际上可以看到图像)

答案 1 :(得分:0)

$('#preload img[src*=keyword]');找不到任何内容,img内没有#preload。您应该为每个id定义li,这些ID将与您的关键字相同。之后,您可以执行$('#preload #' + keyword).text() - 这将返回正确的new_src

<强>更新 编辑后:不要将图像放在li内!这将不必要地增加流量!只放源:

 <li id="kly">pathto.jpg</li>