3

嗨,我实际上是使用 javascript 和 html/css 的新手。

我不明白为什么我的脚本适用于 safari,但不适用于 chrome 和 firefox ......有什么想法吗?

编辑:在 chrome 和 firefox 中,ul 和 li 元素都不会显示......而且之前的警报也不起作用。我将在控制台中检查错误并再次编辑帖子

<!DOCTYPE html>
<html>
    <head>
        <script src="http://code.jquery.com/jquery-latest.js"></script>
    </head>
    <body>
        <div id="patients" style="text-align:center">

        </div>
        <script type="text/javascript">
            $.getJSON("http://www.url.com/json",
                      function(data) {

                      var items = [];
                      alert(data[1].patient);
                      alert(data[1].hr);

                      $.each(data, function(index, val) {
                             items.push('<li id="' + index + '">' + val.patient + '<div style="display: none" id="'+val.patient+'"></div></li>');
                             });

                      $('<ul/>', {
                        'class': 'my-new-list',
                        html: items.join('')
                        }).appendTo('#patients');


                      });
            </script>

    </body>
</html>
4

1 回答 1

3

The first thing you have to understand is when javascript executes on the page.

So in the code you have posted, the browser first loads the jquery library. When it encounters your <script> tag, it then attempts to execute the $.getJSON() function.

In your script, on the successful completion of the json request, its attempting to modify the DOM by adding generated html to #patients. This won't work 100% of the time because you can't guarantee the browser has rendered #patients yet.

You should start by wrapping your javascript code inside a wrapper that only executes after page load.

This can be done in a few ways. These are the jQuery specific methods here, since that's what you're using.

$(document).ready(function(){
    //your code
});

Or:

$(function(){
    //your code
});

The native javascript code would look something like:

document.addEventListener('load', function(){
    //your code
}, false);

I would recommend using one of the jQuery methods.

As an added tip, you don't need to put type="text/javascript" in your script tag. All browsers understand that a script tag means javascript. Luckily we are well past the old days of various broken versions of Internet Explorer.

于 2012-07-30T11:15:42.600 回答