-1

我对这段代码有一个非常奇怪的问题:在这个小提琴中,它提醒“红色”的索引为 0(我想提醒),但在我的本地计算机上它提醒检查不起作用......有人可以告诉我为什么会这样?

  <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
  <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
  <head>
  <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-2" />
  <meta name="author" content="Dejan Peic"/>
  <meta name="description" content=""/>
  <meta name="keywords" content=""/>



 <style type="text/css">
 .wrapper{
 width:100px;
 height:150px;
 border:1px solid #000000;
 margin:0auto;
 position:relative;
 display:block;
 }
 .red{
 width:100px;
 height:50px;
 display:block;
 background-color:red;
 }
 .blue{
 width:100px;
 height:50px;
 display:block;
 background-color:blue;
 }
.green{
 width:100px;
 height:50px;
 display:block;
 background-color:green;
 }
.checkIndex{
width:150px;
height:20px;
background-color:black;
color:white;
}
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"  type="text/javascript"></script>
  <script type="text/javascript">

  var red = $('.red');
  var active = $('.active');
  var redIndex = red.index();
  var activeIndex = active.index();
  $(document).ready(function(){
  $('.wrapper div:last').addClass('active');

  $('.checkIndex').click(function(){

  if(redIndex > activeIndex){
  alert('Red has index 0');
  }

  else{
  alert('check doesnt work :(');
  }

  });

  });
  </script>
  </head>
  <body>
  <div class="wrapper">
  <div class="red"></div>
  <div class="blue"></div>
  <div class="green"></div>
  </div><!--/wrapper-->
  <div class="checkIndex">Check index of RED</div>

  </body>
  </html>
4

1 回答 1

3

您需要移动这些行:

var red = $('.red');
var active = $('.active');
var redIndex = red.index();
var activeIndex = active.index();

在你的$(document).ready(...)函数里面。

在该函数之外,指定的 DOM 元素尚不存在。

它仅适用于 jsfiddle,因为默认情况下,该站点会自动将您的代码包装在onload处理程序中,从而达到相同的效果。

于 2012-04-13T13:31:14.370 回答