Jquery 立即声明变量



如何声明jquery变量以在每个函数/事件中使用? 我的脚本看起来很"丑陋",在每个事件中重复声明 var,如何更改"一劳永逸"的 var 并在文档中使用?

$(document).ready(function(){
    var keyword = $("#autocomplete").val();
        group = <?php echo $tb->group ?>;
        uid = <?php echo $tb->uid ?>;
    loadData(1, group, uid, '');
    $('#btn_search').click(function(){
        var keyword = $("#autocomplete").val();
            group = <?php echo $tb->group ?>;
            uid = <?php echo $tb->uid ?>;
        loadData(1,group,uid,keyword);
    });
    $('body').on('click touchend', '#list-container .pagination li.go', function(){
        var page = $(this).attr('p');
            group = <?php echo $tb->group ?>;
            uid = <?php echo $tb->uid ?>;
            keyword = $("#autocomplete").val();
        loadData(page,group,uid,keyword);
    });
});
function loadData(page,group,uid,keyword){
    $.ajax({
        type: "POST",
        url: "process.php",
        data: { 
            page:page,
            group:group,
            uid:uid,
            keyword:keyword 
        },
        success: function(response){
            $('#output').html(response.html);
        }
    });
}

声明变量而不带 var 关键字那么它将是窗口对象内部的全局变量

    keyword = $("#autocomplete").val();
    group = <?php echo $tb->group ?>;
    uid = <?php echo $tb->uid ?>;

像这样使用

    window.keyword = $("#autocomplete").val();
    window.group = <?php echo $tb->group ?>;
    window.uid = <?php echo $tb->uid ?>;

修改了您的代码

$(document).ready(function(){
        keyword = $("#autocomplete").val();
        group = <?php echo $tb->group ?>;
        uid = <?php echo $tb->uid ?>;
    loadData(1, group, uid, '');
    $('#btn_search').click(function(){
        loadData(1,group,uid,keyword);
    });
    $('body').on('click touchend', '#list-container .pagination li.go', function(){
        var page = $(this).attr('p');
        loadData(page,group,uid,keyword);
    });
});
function loadData(page,group,uid,keyword){
    $.ajax({
        type: "POST",
        url: "process.php",
        data: { 
            page:page,
            group:group,
            uid:uid,
            keyword:keyword 
        },
        success: function(response){
            $('#output').html(response.html);
        }
    });
}

相关内容

  • 没有找到相关文章

最新更新