如何在jQuery中使用$('document').ready(函数())?

时间:2021-01-19 00:08:48

I have a piece of code that is working fine in IE, but it doesn’t run in Firefox. I think the problem is that I have not been able to implement $('document').ready(function). The structure of my json is like [{"options":"smart_exp"},{"options":"user_intf"},{"options":"blahblah"}]. I will be very thankful if someone can see my code & help me in correctly implementing it. Here is my code:

我有一段代码在IE中运行良好,但在Firefox中没有运行。我认为问题是我没有实现$('document').ready(函数)。我的json结构就像{“选项”:“smart_exp”},{“选项”:“user_intf”},{“选项”:“blahblah”}。如果有人能看到我的代码并帮助我正确地实现它,我将非常感激。这是我的代码:

<html><head>
     <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2
     /jquery.min.js"></script>
     <script type="text/javascript" language="javascript">
     $(document).ready(function() { 
     $.getJSON("http://127.0.0.1/conn_mysql.php", function (jsonData) {
     $.each(jsonData, function (i, j) {
     document.form1.fruits.options[i] = new Option(j.options);
     });});
     });
     </script></head>
     <body><form name="form1">
     My favourite fruit is :
     <select name="fruits" id="fruits" /></form></body>
</html>

5 个解决方案

#1


2  

Just run $(document).ready(function() {doStuff}). This will automatically run when the document is ready.

只运行$(文档)时(函数(){ doStuff })。这将在文档准备就绪时自动运行。

It's best practice, at least in my opinion, that you don't put any events in the html itself. This way you separate the structure of an html document from it's behavior. Instead attach events in the $(document).ready function.

至少在我看来,最好的做法是,不要将任何事件放到html中。这样就可以将html文档的结构与它的行为分离开来。而是在$(文档)中附加事件。准备功能。

<html>
  <head>
     <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
     <script type="text/javascript">
       $(document).ready(function() { 
           $.getJSON("http://localhost/conn_mysql.php", function (jsonData) {
             var selectElem = $('#fruits');

             for(var i = 0; i < jsonData.length; i++) { 
               selectElem.append($('<option>').html(jsonData[i].options));
             }

           });
       });
     </script>
  </head>
  <body>
    <form name="form1">
      My favourite fruit is :
      <select name="fruits" id="fruits" />
    </form>
  </body>
</html>

EDIT: I tested with the following and mocked the json object since I can't make that call myself.

编辑:我用下面的方法测试了json对象,因为我自己不能调用它。

<html>
  <head>
     <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
     <script type="text/javascript">
       $(document).ready(function() {
           var jsonData = JSON.parse('[{"options":"smart_exp"},{"options":"user_intf"},{"options":"blahblah"}]');
           var selectElem = $('#fruits');

           for(var i = 0; i < jsonData.length; i++) { 
             selectElem.append($('<option>').html(jsonData[i].options));
           }

       });
     </script>
  </head>
  <body>
    <form name="form1">
      My favourite fruit is :
      <select name="fruits" id="fruits" />
    </form>
  </body>
</html>

#2


4  

Short version (suggested by meeger): don't use single quotes around document.

短版本(meeger建议):不要在文档周围使用单引号。

document is a variable that comes with JavaScript (at least in the browser context). Instead, try the following for the relevant line.

文档是一个带有JavaScript的变量(至少在浏览器中是这样)。相反,请尝试以下相关的行。

$(document).ready(function() {

$(文档)时函数(){

You'll also want to take the onLoad attribute off of the body tag, else it will run twice.

您还需要将onLoad属性从body标记中删除,否则它将运行两次。

#3


2  

Here it is in all its glory. The shorthand, awesome version:

这就是它的全部荣耀。速记,很棒的版本:

UPDATED

更新

<script type="text/javascript" language="javascript">
    $(function() { 
        $.getJSON("http://localhost/conn_mysql.php", function (jsonData) {
            var cacheFruits = $('#fruits'),
                cacheOption = $(document.createElement('option'));

            $.each(jsonData, function (i, j) {
                cacheFruits.append(
                    cacheOption.clone().attr('value', j.options).html(j.options)
                );
            });
        });
    });
</script>

Of course, I don't know what your JSON structure is, so you may need to play around with the append section of the code.

当然,我不知道您的JSON结构是什么,所以您可能需要使用代码的附加部分。

There should be no reason why the above would not work.

没有理由说上述理由行不通。

#4


0  

You do not need quotes around document. Once the page has completely loaded, it will start executing whatever you have defined in ready()

您不需要在文档周围引用。一旦页面完全加载,它将开始执行您在ready()中定义的任何内容

$(document).ready(function() { 
  $(this).getJSON("http://localhost/conn_mysql.php", function (jsonData) {
    $(this).each(jsonData, function (i, j) {
      document.form1.fruits.options[i] = new Option(j.options);
    });
  });
});

#5


0  

Try this, your json data should be in this format:

试试这个,你的json数据应该是这样的:

[{'text':'sometext','value':'somevalue'},{'text':'sometext','value':'somevalue'}];


$(document).ready(function() { 
  $(this).getJSON("http://localhost/conn_mysql.php", function (jsonData) {
    var options = [];
    $.each(jsonData, function (i, j) {
      options.push('<option value="' + j.value + '">'  + j.text + '</option>');
    });
    $('#fruits').html( options.join(''));
  });
});

Please note that there may be an encoding/escaping issues here. Make sure that you escape the text properly from the server side. htmlentities, htmlspecialchars can help you with that.

请注意,这里可能存在编码/转义问题。确保您从服务器端正确地脱离了文本。htmlentities, htmlspecialchars可以帮助您。

This should work in most browsers

这应该适用于大多数浏览器。

#1


2  

Just run $(document).ready(function() {doStuff}). This will automatically run when the document is ready.

只运行$(文档)时(函数(){ doStuff })。这将在文档准备就绪时自动运行。

It's best practice, at least in my opinion, that you don't put any events in the html itself. This way you separate the structure of an html document from it's behavior. Instead attach events in the $(document).ready function.

至少在我看来,最好的做法是,不要将任何事件放到html中。这样就可以将html文档的结构与它的行为分离开来。而是在$(文档)中附加事件。准备功能。

<html>
  <head>
     <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
     <script type="text/javascript">
       $(document).ready(function() { 
           $.getJSON("http://localhost/conn_mysql.php", function (jsonData) {
             var selectElem = $('#fruits');

             for(var i = 0; i < jsonData.length; i++) { 
               selectElem.append($('<option>').html(jsonData[i].options));
             }

           });
       });
     </script>
  </head>
  <body>
    <form name="form1">
      My favourite fruit is :
      <select name="fruits" id="fruits" />
    </form>
  </body>
</html>

EDIT: I tested with the following and mocked the json object since I can't make that call myself.

编辑:我用下面的方法测试了json对象,因为我自己不能调用它。

<html>
  <head>
     <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
     <script type="text/javascript">
       $(document).ready(function() {
           var jsonData = JSON.parse('[{"options":"smart_exp"},{"options":"user_intf"},{"options":"blahblah"}]');
           var selectElem = $('#fruits');

           for(var i = 0; i < jsonData.length; i++) { 
             selectElem.append($('<option>').html(jsonData[i].options));
           }

       });
     </script>
  </head>
  <body>
    <form name="form1">
      My favourite fruit is :
      <select name="fruits" id="fruits" />
    </form>
  </body>
</html>

#2


4  

Short version (suggested by meeger): don't use single quotes around document.

短版本(meeger建议):不要在文档周围使用单引号。

document is a variable that comes with JavaScript (at least in the browser context). Instead, try the following for the relevant line.

文档是一个带有JavaScript的变量(至少在浏览器中是这样)。相反,请尝试以下相关的行。

$(document).ready(function() {

$(文档)时函数(){

You'll also want to take the onLoad attribute off of the body tag, else it will run twice.

您还需要将onLoad属性从body标记中删除,否则它将运行两次。

#3


2  

Here it is in all its glory. The shorthand, awesome version:

这就是它的全部荣耀。速记,很棒的版本:

UPDATED

更新

<script type="text/javascript" language="javascript">
    $(function() { 
        $.getJSON("http://localhost/conn_mysql.php", function (jsonData) {
            var cacheFruits = $('#fruits'),
                cacheOption = $(document.createElement('option'));

            $.each(jsonData, function (i, j) {
                cacheFruits.append(
                    cacheOption.clone().attr('value', j.options).html(j.options)
                );
            });
        });
    });
</script>

Of course, I don't know what your JSON structure is, so you may need to play around with the append section of the code.

当然,我不知道您的JSON结构是什么,所以您可能需要使用代码的附加部分。

There should be no reason why the above would not work.

没有理由说上述理由行不通。

#4


0  

You do not need quotes around document. Once the page has completely loaded, it will start executing whatever you have defined in ready()

您不需要在文档周围引用。一旦页面完全加载,它将开始执行您在ready()中定义的任何内容

$(document).ready(function() { 
  $(this).getJSON("http://localhost/conn_mysql.php", function (jsonData) {
    $(this).each(jsonData, function (i, j) {
      document.form1.fruits.options[i] = new Option(j.options);
    });
  });
});

#5


0  

Try this, your json data should be in this format:

试试这个,你的json数据应该是这样的:

[{'text':'sometext','value':'somevalue'},{'text':'sometext','value':'somevalue'}];


$(document).ready(function() { 
  $(this).getJSON("http://localhost/conn_mysql.php", function (jsonData) {
    var options = [];
    $.each(jsonData, function (i, j) {
      options.push('<option value="' + j.value + '">'  + j.text + '</option>');
    });
    $('#fruits').html( options.join(''));
  });
});

Please note that there may be an encoding/escaping issues here. Make sure that you escape the text properly from the server side. htmlentities, htmlspecialchars can help you with that.

请注意,这里可能存在编码/转义问题。确保您从服务器端正确地脱离了文本。htmlentities, htmlspecialchars可以帮助您。

This should work in most browsers

这应该适用于大多数浏览器。