jQuery函数仅适用于重载

时间:2012-06-17 21:48:31

标签: jquery jquery-mobile

我有以下非常简单的代码片段,它从一个单独的文件加载到我正在构建的多页网站中的一个jQuery Mobile页面中:

$(document).ready(function(){
    $('select[name="state_choice"]').change(function(){
        var thisState = $(this).val();
        var indexState = '#' + thisState;
        $('.state').hide();
            $(indexState).show();
      });
})

它正在运行,但现在它只在我重新加载页面时才有效。我正在使用Firebug检查页面加载,并且它没有一直加载jQuery文件,因为这个链接在重新加载之前没有显示。

<script src="inc/jquery/belmont.custom.js"></script>

通常,控制台将显示何时在jQuery mobile中调用新页面,但我确实发现当单击指向该链接时,该特定页面并未始终显示在控制台日志中。我已经在台式机模拟器(Dashcode的iOS模拟器),桌面浏览器(FF和Safari)以及我的iPhone上测试了所有相同的结果。

有没有人见过这种行为?我怎样才能确保这种方法一致?

编辑:我已将代码更改为使用bind,如下所示:

$(document).bind('pageinit', function(){
    $('select[name="state_choice"]').change(function(){
        var thisState = $(this).val();
        var indexState = '#' + thisState;
        $('.state').hide();
        $(indexState).show();
    });
})

我已将console.log(indexState)添加到该函数中,但这也不会持续触发。

我之前实际上说错了 - 这是一个由单页组成的移动网站。我是否必须将jQuery自定义函数脚本加载到每个页面中?或者我可以将它加载到有问题的那个?

1 个答案:

答案 0 :(得分:0)

以下是我如何整理出来的。由于jQM使用AJAX加载每个后续页面,因此您需要将此类交互视为任何其他动态加载的元素。将bind()更改为on()(我使用的是jQuery 1.7+)可以使一切正常运行:

$('body').on('pageinit', '#id_of_page_using_function', function(){
    $('select[name="state_choice"]').change(function(){
        var thisState = $(this).val();
        var indexState = '#' + thisState;
        $('.state').hide();
        $(indexState).show();
    });
})
相关问题