繁体   English   中英

如何使用Jquery在Javascript中加载页面时调用函数

[英]How to call a function when a page loads in Javascript with Jquery

<script type="text/javascript" >

        function getDetails() {
            var IDex = getQueryStringVariableByName("GameID");

            $.ajax({
                type: "POST",
                url: "http:/...",
                data: "{'ItemID': '" + escape(IDex) + "'}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) {
                    var data = response.d;
                    $('#output').empty();
                    $.each(data, function (index, item) {
                        var str = "Title: " + item.Name + "<br /> Current Price: " + item.CurrentPrice + "<br /> Developer: " + item.Developer + "<br /> Genres: " + item.Genre
                        $('#output').append('<li>' + str + '</li>');
                    });
                },
                failure: function (msg) {
                    $('#output').text(msg);
                }
            });
        }


         function getQueryStringVariableByName(name) {
             //use this function by passing it the name of the variable in the query
             //string your are looking for.  For example, if I had the query string
             //"...?id=1" then I could pass the name "id" to this procedure to retrieve
             //the value of the id variable from the querystring, in this case "1".
             name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
             var regexS = "[\\?&]" + name + "=([^&#]*)";
             var regex = new RegExp(regexS);
             var results = regex.exec(window.location.search);
             if (results == null)
                 return "";
             else
                 return decodeURIComponent(results[1].replace(/\+/g, " "));
         }

         window.onload = GetDetails;
         //$(document).ready( function () {
         //    getDetails();
         //
</script>

我已经尝试了多种方法来在页面加载时运行getDetails。 我已经尝试了window.onload方法,将它放在body标签中,还有其他几个,但我似乎找不到让它自动加载的方法。

它应该是getDetails或你可以使用:

$(document).ready(function(){
  functionname();
});

检查编译器是否在页面加载时实际读取代码

$(document).ready(function() { 
    getDetails();
});

function getDetails() { 
   alert("this is a try");
   //or
   console.log("this is a try");
}

当然也包括你的文档的jquery框架

<script src = "path" type = "text/javascript"></script>

最好的方法是在必须关闭body标签之前编写它

希望能帮助到你!

我不确定我是否理解这个问题,但是在jQuery加载后页面运行函数的方法是这样的:

$(document).ready(function() {

    // Your code goes here..
    myFunction();

});

它不起作用?

$(function(){
         getDetails();
    });
$(document).ready(function() {
   getDetails();
});

肯定会工作的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM