如何在下面的 jQuery 代码中设置闪烁文本:
for(var i in list)
{
html += '<td class="box"><span class="Ashar">'+ list[i]+'<div class="timeValue">'+ times[list[i].toLowerCase()]+'</div></span></td>';
if(jsonStr.currentTime == times[list[i].toLowerCase()]+":00")
{
$("#audio").html('<audio style="width: 100%;" class="audioDemo" controls preload="none" controlsList="nodownload"><source src="assets/audio/alarm1.mp3" type="audio/mpeg"></audio>');
$(".audioDemo").trigger("play");
$('.Ashar').blink(); // I want to put it here
}
}
html += '</table>';
document.getElementById('todayPrayTime').innerHTML = html;
如果我在循环内和 document.getElementById('todayPrayTime').innerHTML = html;
之前设置 $('.Ashar').blink();
它不会工作。眨眼不起作用。
但是如果我把 document.getElementById('todayPrayTime').innerHTML = html;
它可以工作,我可以看到闪烁的文字。
我相信这是因为我在 document.getElementById('todayPrayTime').innerHTML = html;
声明之前放置了 $('.Ashar').blink();
.
有什么办法吗?
更新
闪烁函数
(function($)
{
$.fn.blink = function(options) {
var count = 1;
var defaults = {
delay: 500
};
var options = $.extend(defaults, options);
return this.each(function() {
var obj = $(this);
setInterval(function() {
if ($(obj).css("visibility") == "visible") {
$(obj).css('visibility', 'hidden');
}
else {
$(obj).css('visibility', 'visible');
}
}, options.delay);
});
}
}(jQuery));
最佳答案
问题确实是您在将 html 添加到页面之前放置了 blink()
,这意味着选择器没有找到任何元素。
要解决这个问题,您可以在代码末尾添加调用。由于您不希望所有元素都闪烁,只希望那些符合条件的元素闪烁,因此您可能需要添加另一个类来解决这个问题:
for(var i in list)
{
//Create a var to keep the class.
var tClass = list[i];
if(jsonStr.currentTime == times[list[i].toLowerCase()]+":00")
{
$("#audio").html('<audio style="width: 100%;" class="audioDemo" controls preload="none" controlsList="nodownload"><source src="assets/audio/alarm1.mp3" type="audio/mpeg"></audio>');
$(".audioDemo").trigger("play");
//Add another class to the var:
tClass += " blinker";
}
//Adapt the html var
html += '<td class="box"><span class="'+ tClass+'">'+ list[i]+'<div class="timeValue">'+ times[list[i].toLowerCase()]+'</div></span></td>';
}
html += '</table>';
document.getElementById('todayPrayTime').innerHTML = html;
//Only make the ones with the "blinker" class blink.
$('.blinker').blink(); // I want to put it here
这将使事物闪烁,就像您希望的那样。
关于javascript - jQuery 在 innerHTML 声明之前设置闪烁文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47032563/