开发者

Problem with jQuery array

<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js" type="text/javascript"></script>
<script type="text/jscript">
    $('document').ready(function (){
        var clickNo=0;
        $('div#pics>img').hide()
        $('div#pics>input').click(function(event){
            $('div#pics>img')[0].show('slow');
        })

    });
</script>
</head>
<body>
<div id="pics">
<input type="button" value="next" />
<--a bunch of img tags .I had to resort to this comment bec开发者_运维技巧ause the system won't 
   let me include the img tag in the code-->
</div>
</body>
</html>

I can't understand why the line $('div#pics>img')[0].show('slow'); is not working.


This gets the native DOM element, not the jQuery object (which doesn't have a .show() function), what you want instead is :first like this so you get the jQuery object:

$('div#pics>img:first').show('slow');

Or, in your current format, get the first match like this:

$('div#pics>img:eq(0)').show('slow');
//Or..
$('div#pics>img').eq(0).show('slow');

I assume that number will change/climb, so the last option seems like the best approach in your case.


I have several pieces of advice:

  1. If the images are meant to be hidden on page load, hide them with CSS not Javascript;

  2. There is little value in specifying a tag name and an ID (div@pics). Just specify the ID (#pics);

  3. The array notation ([0]) is shorthand for get(0). It returns a DOM element and not a jQuery object. The jQuery object is the one that has a show() method; and

  4. jQuery is up to 1.4.2; and

  5. I'm not sure exactly what you're trying to do with your click() handler. The name "next" implies you want to cycle through them?

Incorporating all that:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
  "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<style type="text/css">
#pics img { display: none; }
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"></script>
<script type="text/jscript">
$(function() {
  $("#pics > input").click(function(event) {
    var images = $("#pics img");
    var visible = images.filter(":visible");
    if (visible.length == 0) {
      images.eq(0).show("slow");
    } else {
      var index = images.index(visible[0]);
      visible.hide("slow");
      $(images[(index + 1) % images.length]).show("slow");
    }
  });
});
</script>
</head>
<body>
<div id="pics">
<input type="button" value="next" />
<--a bunch of img tags .I had to resort to this comment because the system won't 
   let me include the img tag in the code-->
</div>
</body>
</html>
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜