如何更改hascchange

时间:2015-05-07 15:15:33

标签: jquery ajax hashchange

我使用Ben Allman的BBQ插件来处理哈希变化。当链接或标签触发哈希更改时,我没有遇到任何问题,但在应用于<select>时需要一些相同功能的帮助。

我可以在选择更改时获取要更改的哈希值和要加载的远程内容,但我希望select选项与url中的哈希值匹配。

因此,当您选择'Car'时,页面将加载相应的远程内容,has将更改为'foo.com/#!Page_Car.php',而select将显示'Car'。这一切都运行正常,但是当我使用浏览器后退按钮触发网址更改时,我希望相同,除了更改选择列表的选定值之外,一切正常。

更新 - 解决了问题

<select name="HashSelect" id="HashSelect" onchange="location = this.options[this.selectedIndex].value;">
    <option value="#!Page_Car.php">Car</option>
    <option value="#!Page_Plane.php">Plane</option>
    <option value="#!Page_Boat.php">Boat</option>      
</select>

和js

$(function(){
    $.param.fragment.ajaxCrawlable( true );
    var cache = {
        '': $('.contentDefault')
    };
    $(window).bind( 'hashchange', function(e) {
        var url = $.param.fragment();
        $( '#content-target' ).children( ':visible' ).hide();
        url && $( 'a[href="#!' + url + '"]' );
        if ( cache[ url ] ) {
            cache[ url ].show();
            $('#HashSelect option').filter(function() {
                return this.value && this.value == location.hash;
            }).prop('selected', true);
        } else {
            $( '#content-loading' ).show();
            cache[ url ] = $( '<div class="content-item"/>' )
            .appendTo( '#content-target' )
            .load( url, function(){
                $( '#content-loading' ).hide();
                //This worked for me
                $('#HashSelect option').filter(function() {
                    return this.value && this.value == location.hash;
                }).prop('selected', true);
            });
            $( '#content-loading' ).hide();
        }
    });
    $(window).trigger( 'hashchange' );
});

0 个答案:

没有答案