简体   繁体   English

全局定义的jQuery变量,但未定义的日志记录

[英]jQuery variable globally defined but logging as undefined

I am making a product image viewer similar to what is on sites like Amazon (you hover over an image, it appears larger -- click the image thumbnail and it sets the main image as what was clicked). 我正在制作类似于Amazon之类的网站上的产品图像查看器(将鼠标悬停在图像上,它看起来更大-单击图像缩略图,将主图像设置为单击的图像)。

Background info aside, I set two global variables outside the functions that control the main image. 除了背景信息,我在控制主图像的函数之外设置了两个全局变量。 Something strange is happening where the variables are only defined up to a certain point in the code execution, then they become "undefined". 发生奇怪的事情是,变量仅在代码执行过程中的某个点被定义,然后变为“未定义”。

Here is my markup: 这是我的标记:

<div id="product-image-gallery">
   <div id="product-image-holder" style="background-image: url('http://example.com/images/main-image.jpg');">My Main Image
   </div>

   <ul>
     <li class="product-thumb">
       <img src="http://example.com/images/image-1.jpg"/>
     </li>
     <li class="product-thumb">
       <img src="http://example.com/images/image-2.jpg"/>
     </li>
   </ul>
</div>

In jQuery, I am storing the original image and image background path in two global variables, then defining the functions that alter the main image container to show the proper image. 在jQuery中,我将原始图像和图像背景路径存储在两个全局变量中,然后定义更改主图像容器以显示正确图像的函数。 Here is my jQuery: 这是我的jQuery:

var $originalImage = $('#product-image-holder');
var $originalImageSrc = $originalImage.css('background-image');

$('#product-image-gallery ul li.product-thumb').click(function () {
    $('li.product-thumb.active').removeClass('active');
    $(this).addClass('active');
});

$('#product-image-gallery ul li.product-thumb').hover(
//mouseenter event
    function () {
        var $imageChange = $(this).find('img');
        var $imageChangeSrc = 'url(\'' + $imageChange.attr('src') + '\')';
        $originalImage.css("background-image", $imageChangeSrc);
},
//mouseleave event
function () {
    var $activeImage = $('#product-image-gallery ul li.product-thumb.active img');
    var $activeImageSrc = 'url(\'' + $activeImage.attr('src') + '\')';

    if($(this).hasClass('active')){
        return;
    }
    else if ($activeImage != '') {
        $originalImage.css("background-image", $activeImageSrc);
    }
    else {
        $originalImage.css("background-image", $originalImageSrc);
    }
});

When I view the page, all works as expected on mouse hover, except the original image path resets itself to undefined (I can witness this behavior in the console). 当我查看页面时,所有操作都可以在鼠标悬停时按预期进行,除了原始图像路径会将其自身重置为undefined(我可以在控制台中看到此行为)。 I am completely stumped as to what could cause this to happen. 对于可能导致这种情况发生的原因,我完全感到困惑。

Any suggestion as to what would make this variable unset itself is greatly appreciated. 任何有关使该变量自身不起作用的建议都将受到赞赏。

[EDIT] Here is a jsfiddle with my example, showing the exact same behavior: https://jsfiddle.net/htxxnfuy/ [编辑]这是带有我的示例的jsfiddle,显示了完全相同的行为: https ://jsfiddle.net/htxxnfuy/

You check if .active image found incorrectly. 您检查.active图片是否正确找到。 Result is a collection of elements with 0 length if nothing matches selector. 如果没有匹配的选择器,则结果是长度为0的元素的集合。

if ($activeImage.length) { // <-- this line
    $originalImage.css("background-image", $activeImageSrc);
}

 var $originalImage = $('#product-image-holder'); var $originalImageSrc = $originalImage.css('background-image'); $('#product-image-gallery ul li.product-thumb').click(function () { $('li.product-thumb.active').removeClass('active'); $(this).addClass('active'); }); $('.product-thumb').hover( //mouseenter event function () { var $imageChange = $(this).find('img'); var $imageChangeSrc = 'url(\\'' + $imageChange.attr('src') + '\\')'; $originalImage.css("background-image", $imageChangeSrc); }, //mouseleave event function () { var $activeImage = $('li.active img'); var $activeImageSrc = 'url(\\'' + $activeImage.attr('src') + '\\')'; if($(this).hasClass('active')){ return; } else if ($activeImage.length) { // <-- this line $originalImage.css("background-image", $activeImageSrc); } else { $originalImage.css("background-image", $originalImageSrc); } }); 
 #product-image-holder { height: 50px; width: 50px; } 
 <script src="https://code.jquery.com/jquery-2.1.4.min.js"></script> <div id="product-image-gallery"> <div id="product-image-holder" style="background-image: url('http://placehold.it/50x50');"> My Main Image </div> <ul> <li class="product-thumb"> <img src="http://placehold.it/52x52"/> </li> <li class="product-thumb"> <img src="http://placehold.it/51x51g"/> </li> </ul> </div> 

You are checking a possible collection of elements against an empty string. 您正在针对空字符串检查可能的元素集合。 When trying to find out if a jQuery selector returns any item (or many), you can test it's length property. 当试图确定jQuery选择器是否返回任何一项(或多项)时,可以测试它的length属性。

I've also reduced your code a bit: 我还减少了您的代码:

$(function () {
    // To make your code a bit easier to understand, use $ to prefix
    // only variables that represent a jQuery selector.
    var $originalImage = $('#product-image-holder');
    var originalImageSrc = $originalImage.css('background-image');
    var containerSelector = '#product-image-gallery ul li.product-thumb';
    var $container = $(containerSelector);

    // You can attach as many event handlers as you need in just
    // one go. Also, it's better to use mouseenter and mouseleave
    // instead of hover.
    $container.on({ click: function () {
            $('li.product-thumb.active').removeClass('active');

            $(this).addClass('active');
    }, mouseenter: function () {
        var $imageChange = $(this).find('img');
        var imageChangeSrc = 'url(\'' + $imageChange.attr('src') + '\')';

        $originalImage.css('background-image', imageChangeSrc);
    }, mouseleave: function () {
        var $activeImage = $(containerSelector + '.active img');
        var activeImageSrc = 'url(\'' + $activeImage.attr('src') + '\')';

        // I would review the necessity of this entire check.
        if ($(this).hasClass('active')) {            
        } else if ($activeImage.length > 0) { 
            // If there's at least one element coming
            // from the selector above.           
            $originalImage.css('background-image', activeImageSrc);
        } else {           
            $originalImage.css('background-image', originalImageSrc); 
        }
    }});
});

Demo 演示版

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM