开发者

Simple jquery script not working in safari

开发者 https://www.devze.com 2023-04-08 19:59 出处:网络
This script works in firefox, IE, and chrome, but not safari. Any ideas? The really strange thing is that when I put an alert() at the end of the .get() callback, it executes (even in safari).So the

This script works in firefox, IE, and chrome, but not safari. Any ideas?

The really strange thing is that when I put an alert() at the end of the .get() callback, it executes (even in safari). So the code isn't crashing, it's just not modifying the DOM.

<html>
<head>
    <title>Title for this webpage</title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js" type="text/javascript"></script>

<!- CSS styling -------------------------------------------------------------->
<style type="text/css"/>
body{
    margin:0px;
    padding:0px;
    font-family:verdana, arial, helvetica, sans-serif;
    font-size:14px;
    text-align:left;

    width:900px;
    margin-left:auto;
    margin-right:auto;
    position:relative;

    background-color:#fff;
}

#mainBox{
    width:700px;
    margin:30px;
    border:2px solid #ddd;
    margin-left:auto;
    margin-right:auto;
}

#mainHeader, #mainFooter, #mainContent{
    margin: 5px;
    padding:10px;
    border: 2px dashed #ddd;
    text-align:center;
}

.shuffleMe{
    margin: 5px;
    padding:10px;
    border: 2px solid开发者_运维问答 #ddd;
    text-align:left;
}
</style>

<!- Jquery/javascript -------------------------------------------------------->
<script type="text/javascript">
//Code modified from: http://stackoverflow.com/questions/1134976/how-may-i-sort-a-list-alphabetically-using-jquery
$(document).ready(function(){
  var my_list = $('.shuffleMe').get();
    my_list.sort(function(){return( Math.random() >.5 );});
    $.each(my_list, function(index, item) { $('#mainContent').append(item); });
});
</script>

</head>

<!- HTML body content -------------------------------------------------------->
<body>
<div id="mainBox">
    <div id="mainHeader"> --- HEADER --- </div>
    <div id="mainContent">
        <div class="shuffleMe">AAA</div>
        <div class="shuffleMe">BBB</div>
        <div class="shuffleMe">CCC</div>
        <div class="shuffleMe">DDD</div>
    </div>
    <div id="mainFooter"> --- FOOTER --- </div>
</div>

</body>
</html>


This is an issue with your sort function. The sort function should return -1 (less), 0 (equals), or 1 (more); it shouldn't return a boolean. The fact that it works in other browsers is a fluke in this case I think.

my_list.sort(function(){return( Math.random() - .5 );});


You need to change your sorting function. See this jsFiddle. This code is working:

var my_list = $('.shuffleMe').get();
my_list.sort(function(){
    return 0.5 - Math.random();
});
$.each(my_list, function(index, item) {$('#mainContent').append(item); });
0

精彩评论

暂无评论...
验证码 换一张
取 消