jQuery找到值,然后替换SRC [英] jQuery find value then replace SRC

查看:66
本文介绍了jQuery找到值,然后替换SRC的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何人都可以看到此代码有问题的地方吗?

Can anyone see anything that is wrong with this code it just isn't working...

我正准备去:

获取#product-variants-option-0的值

get the value of #product-variants-option-0

搜索#preload相关图像和

search #preload for the relevant image and

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

then change div.image img src to that image

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>

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

I'm trying to search an unordered list:

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

我要替换的图像是这样:

The image I'm trying to replace is this:

推荐答案

我看到了一些问题:

  1. 您没有将凯利格林"转换为凯利".
  2. var new_src = $('#preload img[src*=keyword]');中已硬编码了keyword(不是关键字变量的值).
  3. 列表中的li中没有img元素(它们只是直接包含URL作为文本). 您已编辑问题并修复那个.
  4. 如果选择的值不是凯利绿色",则说明您未将其设置为小写,并且根本就没有使用该值.
  5. 您没有检索预加载图像的src属性.
  1. You're not converting "Kelly Green" to "kelly".
  2. The var new_src = $('#preload img[src*=keyword]'); has keyword hardcoded into it (not the value of the keyword variable).
  3. The lis in the list don't have img elements inside them (they just directly contain the URL as text). You've edited the question and fixed that.
  4. If the select value isn't "Kelly Green" you're not making it lower case, and you're not using the value at all.
  5. You're not retrieving the src attribute of the preload image.

如果将列表更改为:

If you change the list to:

<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);
   });
});

在线示例

查尔斯,您要求提供有关如何用不同方式编写的信息,我说我有时间做些事情.抱歉耽搁了,我的真正的工作"需要我一会儿.

Charles, you asked for input on how it might be written differently, and I said I had a minute to do something up. Sorry for the delay, my Real Job needed me for a moment.

我可能会这样处理,并假设您在应用程序的其他位置具有这种选择框,因此,进行泛化是值得的.

I'd probably approach it like this, with the assumption that you have this kind of select box elsewhere in your application and therefore generalization is worthwhile.

  1. 使事物尽可能地可重用(嗯,几乎;我留给读者一点概括性的练习).
  2. 请勿将图片网址存储在一个地方,将选项存储在另一个地方;将它们放在一起,这样它们就可以轻松地来自同一数据源.这样可以减少错误. (例如,在您的问题中,您有四个选项,但是在预加载结构中只有两个选项的图像.现在,如果没有其他选项的图像,则可以将该属性保留为空白或将其设为还是空白,但将它们放在一起/由同一来源生成是一个好主意.)
  3. 使用data-image属性执行#2,该属性从HTML5开始有效,并且在早期版本中完全无害. (详细信息)
  4. 在HTML中不包含用于预加载的标记;生成它.这与#2有关,也与以下事实有关:没有JavaScript的用户不需要预缓存的图像,因为它们不会被使用.因此,不要向他们推销他们不需要的东西.
  1. Make things reusable wherever possible (well, almost; there's one bit of generalization I left as an exercise to the reader).
  2. Don't store the image URLs in one place and the options in another; put them together, so they can both come from the same data source easily. This reduces error. (For instance, in your question, you have four options, but you only have images for two of them in the preload structure. Now, if you don't have images for the others, that's fine, leave the attribute off or make it blank, but keeping things together / generated from the same source is a good idea.)
  3. Do #2 with the data-image attribute, which is valid as of HTML5 and perfectly harmless in earlier versions. (Details)
  4. Don't include the markup for the preloading in the HTML; generate it. This relates to #2, and also to the fact that users who don't have JavaScript don't need the precached images as they won't be used. So don't push them things they don't need.

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>

带有jQuery的JavaScript:

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 (but the live example uses some gravatars, so you can actually see the images)

这篇关于jQuery找到值,然后替换SRC的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆