哈希和数字

Hash and the Numbers

本文关键字:数字 哈希      更新时间:2023-09-26

我在jQuery Elastislide中有一个库。

图库中的每张图片都有相应的哈希。

例如:*www.example.com/gallery.html#4/title_of_the_picture*

因此,当我重新加载第四个图像时,页面会加载第四张图像。

但是,当我在哈希中标题之前没有数字的情况下重新加载时,图片不会加载。

*www.example.com/gallery.html#title_of_the_picture*

我可以删除这个号码吗?如果可以的话,Jquery中要使用的正确代码是什么?

jQuery代码:

Gallery = (function() {
    // index of the current item        
    var imageIndex = 0;
    if (window.location.hash) {
        var imageIndexStr = window.location.hash.replace('#', ''); // remove #
        imageIndex = parseInt(imageIndexStr, 0); // convert to int
    }
    var current = imageIndex;
    // mode : carousel || fullview
    mode = 'carousel',
    // control if one image is being loaded
    anim = false, init = function() {
        // (not necessary) preloading the images here...
        $items.add('<img src="ajax-loader.gif"/><img src="black.png"/>').imagesLoaded(function() {
            // add options
            _addViewModes();
            // add large image wrapper
            _addImageWrapper();
            // show first image
            _showImage($items.eq(current));
        });
    }
}​

代码行:

var imageIndexStr = window.location.hash.replace('#', '');
imageIndex = parseInt(imageIndexStr, 0); // convert to int

我们将尝试将哈希的第一个字符转换为int,但如果第一个字符不是有效的int(就像你所说的那样,如果你删除了4,就会出现这种情况),那么JavaScript将在这一点上出错,不再继续。

此外,根据文档,-0似乎不是parseInt()的有效选项。

编辑:替换了W3Schools 的链接

https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/parseInt