选择后更改图像,在列表中搜索src值jQuery [英] change image upon selection, searching list for the src value jQuery

查看:117
本文介绍了选择后更改图像,在列表中搜索src值jQuery的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

应该清楚我要做什么

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

   });
 });

选择:

<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>

推荐答案

我认为问题出在这行:

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

这将 element 分配给变量new_src,而不是字符串;这意味着当您尝试更改以下行中的src时:

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

您正在将dom节点有效地插入到属性中,这不太可能起作用.

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

尝试:

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

假设$('#preload img[src*="kly"]')以任何方式返回有效的img元素;从我看到的您发布的ul中可以看到它包含文本字符串(但这可能是工作中的Mark-down编辑器).

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.

您是否发现没有图像存在于包含字符串'kly'的#preload ul中?这可能是您遇到的主要问题.我已将该列表复制到 JS Fiddle,出于演示目的,该版本似乎可以正常工作:

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).

这篇关于选择后更改图像,在列表中搜索src值jQuery的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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