简体   繁体   English

你如何在jQuery中使用$('document')。ready(function())?

[英]How do you use $('document').ready(function()) in jQuery?

I have a piece of code that is working fine in IE, but it doesn't run in Firefox. 我有一段代码在IE中工作正常,但它不能在Firefox中运行。 I think the problem is that I have not been able to implement $('document').ready(function) . 我认为问题在于我无法实现$('document').ready(function) The structure of my json is like [{"options":"smart_exp"},{"options":"user_intf"},{"options":"blahblah"}]. 我的json的结构类似于[{“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: 这是我的代码:

<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>

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). document是JavaScript附带的变量(至少在浏览器上下文中)。 Instead, try the following for the relevant line. 相反,请尝试以下相关行。

$(document).ready(function() {

You'll also want to take the onLoad attribute off of the body tag, else it will run twice. 您还需要从body标签中取出onLoad属性,否则它将运行两次。

Just run $(document).ready(function() {doStuff}) . 只需运行$(document).ready(function() {doStuff}) This will automatically run when the document is ready. 这将在文档准备好后自动运行。

It's best practice, at least in my opinion, that you don't put any events in the html itself. 至少在我看来,最佳做法是不在html中放置任何事件。 This way you separate the structure of an html document from it's behavior. 这样您就可以将html文档的结构与其行为分开。 Instead attach events in the $(document).ready function. 而是在$(document).ready函数中附加事件。

<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>

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结构是什么,所以你可能需要使用代码的append部分。

There should be no reason why the above would not work. 应该没有理由说上面的原因是行不通的。

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);
    });
  });
});

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 这适用于大多数浏览器

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

相关问题 你如何在jQuery的document.ready中使用揭示模块模式? - How do you use the revealing module pattern with jQuery's document.ready? 如何将$(document).ready(function()添加到joomla - How do you add $(document).ready(function() to joomla 你什么时候需要使用$(document).ready()? - when do you need to use $(document).ready()? 我是否必须使用为 jQuery 准备的文件? - Do I have to use document ready for jQuery? 使用jQuery,你有两个使用$(document).ready(function()的外部脚本吗? - Using jQuery, can you have two external scripts that use the $(document).ready(function()? 如何在jQuery中声明此函数? $ {document).ready无法正常工作 - How to declare this function in jQuery? $(document).ready is not working 如何在jQuery中使用文档准备功能重定向 - How to redirect with document ready function in jquery 如何在jQuery中合并两个$(document).ready(function() - How to merge two $(document).ready(function() in jQuery 如何将jQuery函数/回调移动到文档就绪 - How to move jquery function/callback into document ready 如何在JS / jQuery中创建更大的逻辑整体(而不是将所有内容都放入document.ready)? - How do you create bigger logical wholes in JS/jQuery (instead of putting everything into document.ready)?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM