-1

このコードには本当に奇妙な問題があります: このFiddleでは、「赤」のインデックスが 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 に答える