如何在不需要单击按钮的情况下显示此jQuery函数的结果?

时间:2016-05-06 09:52:51

标签: javascript jquery

我在下面有这个功能,但是我想让它在Windows上加载并显示结果而不点击按钮。 这是我使用的代码https://raw.githubusercontent.com/SuyashMShepHertz/indexedDB_sample/master/index.html

怎么做?

$("#getBtn").click(function(){
  var type = 'permanent';
  var request = db.transaction(["hashes"],"readwrite").objectStore("hashes").get(type);
  request.onsuccess = function(event){
    $("#result").html("Name : "+request.result.name);    
  };
});

3 个答案:

答案 0 :(得分:0)

只需将其放入$(document).ready,就像这样

$(document).ready(function(){
   var type = 'permanent';
   var request = db.transaction(["hashes"],"readwrite").objectStore("hashes").get(type);
   request.onsuccess = function(event){
      $("#result").html("Name : "+request.result.name);    
   };
});

答案 1 :(得分:0)

只需将您的代码放入

即可
 $( window ).load(function() {
       //Code Here
    });

答案 2 :(得分:0)

如果您在点击时和最初页面加载时都需要它,请将其设为可重复使用的功能:

function doTheThing() {
    var type = 'permanent';
    var request = db.transaction(["hashes"], "readwrite").objectStore("hashes").get(type);
    request.onsuccess = function(event) {
        $("#result").html("Name : " + request.result.name);
    };
}

然后从你需要的两个地方调用它:

  • 页面加载

  • 点击

要在页面加载时调用它,只需确保您的脚本位于HTML的末尾(就在结束</body>标记之前;这是best practice,除非您有充分的理由做某事否则)并称之为:

doTheThing();

如果您不能将脚本放在HTML的末尾,则可以改为使用jQuery的ready回调:

// Concise, but easy to misunderstand:
$(doTheThing);

// Or more verbose but also more clear:
$(document).ready(doTheThing);

(请参阅下面关于直接或间接进行的说明。)

要在点击时调用它,请直接或间接地连接它:

// Directly
$("#getBtn").click(doTheThing);

// Or indirectly
$("#getBtn").click(function() {
    doTheThing();
});

间接挂起它的唯一原因是避免让它接收事件对象jQuery会自动传递它,并避免jQuery检查它的返回值,看它是否应该停止传播并阻止默认事件操作

为了避免创建全局变量,我确保整个事情都在一个范围函数中:

(function() {
    function doTheThing() {
        var type = 'permanent';
        var request = db.transaction(["hashes"], "readwrite").objectStore("hashes").get(type);
        request.onsuccess = function(event) {
            $("#result").html("Name : " + request.result.name);
        };
    }

    doTheThing();

    $("#getBtn").click(doTheThing);
})();