下面我得到了一些代码,它应该延迟2秒并隐藏上一个跨度并显示下一个跨度,但我似乎无法让它工作。
<style>
span{ display:none}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"><script>
<div id="text"></div>
<script>
var text = [
"<span>Sent A blabla</span>",
"<span>sent B</span><span>sent b bbb cont....</span>",
"<span>Sent c...</span><span>Sent C2</span><span>sent c3</span>", ];
var text = text[Math.floor(Math.random() * text.length)];
jQuery('#text').html(text);
jQuery('#text').show();
jQuery('#text span:first').show();
var delay = 2000;
jQuery("#text span").each(function() {
setTimeout( function(){
var el = $(this);
el.prev().hide();
el.show();
}, delay)
delay += 2000;
});
</script>
答案 0 :(得分:1)
由于您使用关键字this
。
在for each语句中,您需要设置一个设置为$(this)的变量,然后在超时中引用该变量。示例如下:
var parent = $(this);
setTimeout( function(){
var el = parent;
el.prev().hide();
el.show();
}, delay)
delay += 2000;
答案 1 :(得分:-1)
代码评论中的全部内容:
jQuery(function( $ ){ // FingerSaver: Use $ in the jQuery scope // It's also a DOM ready!
var delay = 2000; // You know this one :)
var $text = $("#text"); // Cache your parent element
// Elements Array.
// You have multiple SPANS per array key
// (which is odd but OK... here's the array)
var text = [
"<span>Sent A blabla</span>",
"<span>sent B</span><span>sent b bbb cont....</span>",
"<span>Sent c...</span><span>Sent C2</span><span>sent c3</span>",
];
// Append all SPANs to the #text parent:
$text.html( text.join("") );
// All SPANs are now inside #text but are hidden by CSS!
// Get (cache) all appended SPANs
var $spans = $text.find("span");
// OK, how many SPANs we have?
var tot = $spans.length;
// (You had 3 array keys, but) 6 SPAN elements :)
// Start c Counter with a random number
var c = Math.floor(Math.random() * tot);
// Create a function that will loop the texts
(function loop() {
c += 1; // Increment counter
c %= tot; // Reset counter back to 0 on reminder
$spans.fadeOut(500).eq( c ).stop().fadeIn(500);
setTimeout(loop, delay);
}()); // Start!
});
&#13;
#text span{
position:absolute;
display:none;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="text"></div>
&#13;
如果您希望保留多个SPAN元素的集合并显示为GROUPS而不是您需要做的就是将每个SPAN从数组键包装到父包装器中,并且执行与上面相同的操作,而不是通过SPANS运营您对其父母的经营。既然你没有在你的问题中解释得那么好,那么到目前为止我可以给你。