gpt4 book ai didi

javascript - 知道为什么我的 jQuery 无法执行吗?

转载 作者:行者123 更新时间:2023-11-28 21:17:27 25 4
gpt4 key购买 nike

我开始为一个项目构建一个推荐旋转器。奇怪的是,它在上线之前就坏了(之前测试过),我决定废弃它并编写一个新脚本来执行相同的任务。我对 jQuery 比较陌生,并且不太熟悉使用三元运算符,但我想尝试一下。

下面的代码是我正在使用的代码。我相信这段代码应该正确执行,但是如果您将其全部复制到新的 .html 文档中,您会发现它不能正确执行。

我正在寻求任何可以获得的帮助。我一直在努力成长为一名开发人员 - 我不是一个只会盲目复制和粘贴以获得结果的人。我想知道发生了什么事:)

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>

<title>Rotator Testing</title>

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>

<style type="text/css">
#testimonials{
width:300px;
height:100px;
background:#666;
position:absolute;
top:0;left:0;
}
.testimonial{
color:#CCC;
display:block;
width:200px;
height:30px;
background:#333;
position:absolute;
left:0;top:0;
z-index:5;
}
.show{
z-index:10;
}
</style>

<script type="text/javascript">
$(document).ready(function(){
$('.testimonial').css({opacity: 0.0});
$('.testimonial:first').css({opacity:1.0});
setInterval(function(){

var current = ( $('#testimonials .testimonial.show')? $('#testimonials .testimonial.show') : $('#testimonials .testimonial:first'));
var next = current.next().length ? $('#testimonials .testimonial:first') : current.next();

//Set the fade in effect for the next testimonial, show class has higher z-index
next.css({opacity: 0.0})
.addClass('show')
.animate({opacity: 1.0}, 1000);

//Hide the current testimonial
current.animate({opacity: 0.0}, 1000)
.removeClass('show');


},2000);
});
</script>



</head>

<body>

<div id="testimonials">
<article class="testimonial">Testimonial 1</article>
<article class="testimonial">Testimonial 2</article>
<article class="testimonial">Testimonial 3</article>
<article class="testimonial">Testimonial 4</article>
</div>

</body>
</html>

最佳答案

var current = ( $('#testimonials .testimonial.show')? $('#testimonials .testimonial.show') : $('#testimonials .testimonial:first'));

jQuery 将始终返回一个对象(即使选择器不匹配任何元素),因此您的条件:

$('#testimonials .testimonial.show')

...永远是真的。

检查长度:

   var current = ( $('#testimonials .testimonial.show').length)
? $('#testimonials .testimonial.show')
: $('#testimonials .testimonial:first');
<小时/>

下一期:

var next = current.next().length ? $('#testimonials .testimonial:first') : current.next();

我想你需要将其切换为:

var next = (!current.next().length) 
? $('#testimonials .testimonial:first')
: current.next();

当前,如果 .next() 为空,则选择它。

关于javascript - 知道为什么我的 jQuery 无法执行吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7237696/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com