此脚本适用于firefox,IE和chrome,但不适用于Safari。有什么想法吗?
真正奇怪的是,当我在alert()
回调的末尾放置.get()
时,它会执行(即使在safari中)。所以代码没有崩溃,只是没有修改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>
答案 0 :(得分:3)
这是您的排序功能的问题。 sort函数应返回-1(less),0(equals)或1(more);它不应该返回布尔值。在我看来,它在其他浏览器中运行的事实是侥幸。
my_list.sort(function(){return( Math.random() - .5 );});
答案 1 :(得分:3)
您需要更改排序功能。见jsFiddle。这段代码正在运行:
var my_list = $('.shuffleMe').get();
my_list.sort(function(){
return 0.5 - Math.random();
});
$.each(my_list, function(index, item) {$('#mainContent').append(item); });