change image upon selection, searching list for the src value jQuery

给你一囗甜甜゛ 提交于 2019-12-13 07:41:29

问题


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

Should be clear what I am trying to do

 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*="kly"]');

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

   });
 });

The selection:

<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>0z-kelly-green-medium.jpg</li>
<li>0z-olive-medium.jpg</li>
</ul>

回答1:


I believe that the problem is this line:

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

This assigns an element to the variable new_src, rather than a string; which means that when you try to change the src in the following line:

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

You're effectively inserting a dom node into an attribute, which is unlikely to work.

Try:

var new_src = $('#preload img[src*="kly"]').attr('src');

Assuming that $('#preload img[src*="kly"]') returns a valid img element, any way; from what I can see of your posted ul it contains text strings (but that could be the Mark-down editor at work).


Edited in response to further comments.

Has it occurred to you that no image exists in the #preload ul that contains the string 'kly'? This is, probably, the main problem you're having. I've copied the list over to JS Fiddle, for demo purposes and this version seems to work:

$('select').change(
    function(){
        if ($(this).val().toLowerCase() == 'kelly green') {
            var keyword = 'kelly';
        }
        else {
            var keyword = $(this).val().toLowerCase();
        }
        $('#alert').text($('#preload img[src*='+keyword+']').attr('src'))
    });

It could certainly be prettified, but it does work (at least given the information I've got so far).



来源:https://stackoverflow.com/questions/4504824/change-image-upon-selection-searching-list-for-the-src-value-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!