【问题标题】:How to trigger or call jquery load function multiple times?如何多次触发或调用jquery加载函数?
【发布时间】:2016-01-03 02:09:59
【问题描述】:

我需要一点帮助。我正在为一些问题苦苦挣扎一段时间。每次单击按钮时,我都需要调用 jquery 加载函数。要触发加载功能,我想我需要刷新该特定 div 或再次加载该 div。

我的目标是:

当我单击按钮时,我希望显示 loading-div 并希望 .image-container 再次加载。我想这应该会触发 jquery 加载函数,该函数将在 .image-container 加载时隐藏 loading-div。

这是我的代码:

$(".image-container").load(function(){
   $( "#loading-div" ).hide();
});

$("#button").on('click', function(){
   $( "#loading-div" ).show();
   $(".image-container").load("index.php"); // load again div that sholud trigger upper function
});

【问题讨论】:

  • 因为它已经加载了..它可能需要回调??

标签: javascript jquery


【解决方案1】:

试试这个

$("#button").on('click', function(){
    $( "#loading-div" ).show();
    $(".image-container").load("index.php", function () {
        $( "#loading-div" ).hide();
    });
});

【讨论】:

  • 它只显示 div 但不隐藏它。我已将警报置于隐藏功能之上,但它没有调用它
【解决方案2】:

假设我想将数据从服务器连续加载到特定的 div 标签。 为此,我使用 setinterval jquery 方法。 示例:

setinterval(function(){
$("div1").load("url","data you want to send to your  server");                      
                      },1000); 

注意:加载方法仅适用于'get'方法。在上面的代码中,加载的第二个参数是可选的。

【讨论】:

    【解决方案3】:

    嗯,只需将所需的预加载/加载后逻辑与处理程序分开?

    function loadSome(el, data) {
       $("#loading-div").show();
       el.load(data, function () {
         $("#loading-div").hide();
       });
    }
    
    function loadImage() {
        loadSome($(".image-container"), "index.php");
    }
    
    loadImage();
    $("#button").on('click', function(){
        loadImage();
    });
    

    或者更多jQuery-way:

    jQuery.fn.progressedLoad = function (data, progressElement) {
        $(progressElement).show();
        // add more complex load-progress logic here...
    
        return this.load(data, function() {
            $(progressElement).hide();
        });
    }
    
    ...
    
    $(".image-container").progressedLoad(
        {"url": "index.php"}, 
        $("#loading-div")
    );
    

    【讨论】:

    • 我得到的结果与上面的答案相同,它只显示但它不隐藏 loading-div
    • 1) 是加载到.image-container 的所需内容,还是只显示#loading-div 然后什么都不做? 2)你使用哪个版本的jQuery? .load() 可以有不同的参数列表,并且在 1.9 之前的 jQuery 版本中的某些用例中的行为类似于 .on("load", function(){})
    • 1) 每次我点击 .image-container 的按钮内容时都会发生变化,但有时会持续几秒钟,所以我创建了显示#loading-div 直到加载完成的函数 2) jquery-2.1 .3
    • 这很奇怪,因为它对我来说很好用。嗯......所以:1)控制台中有什么?加载时有任何错误吗? 2) #loading-div.image-container 内,或者它可能以其他方式发生变化,所以 $("#loading-div") 引用变得无效?你试过$(".image-container").progressedLoad({"url": "index.php"}, "#loading-div");吗? 3)是否可能存在参数列表差异?你也试过$(".image-container").progressedLoad("index.php", "#loading-div");吗? 4)您是否尝试过在 jsFiddle 之类的东西上创建最小的可重现示例?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多