change image upon selection, searching list for the src value jQuery
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>
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).
精彩评论