私は1秒ごとに新しい利用可能な広告をチェックし、前の広告の表示が終了した場合にのみ表示する広告システムを構築しようとしています。 (各広告には、表示する秒数を指定する 'time'という名前の属性があります)インターバル関数内のDOMへのjQueryの変更はスティックではありません
私は 'setInterval()'を使ってプログラムを実装しました。開いているスロットがあるときはいつでも、 '.load()'を使用して、 '.html()'と '.attr( "src"、...)'を使用してテキストと画像を広告のテキストと画像に変更します。
ファイルを実行すると、1秒間広告が表示されます(4秒間でなければなりません)。その後、DOMは 'template.html'の元のテキストと画像に復元されます。この操作は無限に実行されますが、4秒ごとに広告が一瞬表示され、DOMが復元されます。
私は類似の問題についてここで多くの記事を読んでいますが、この特定の問題の解決策はありませんでした。
はここで広告オブジェクトが格納されているプレイリストです。ここではjQueryを使用して区間内のDOMの変更だ
{name: "msg1",
texts: {txt1: "First ad!",
txt2: "Come and buy our product!",
txt3: "It's top secret...",
txt4: "So it has to be good ;)"},
images: {img1: "./topSecret.png",
img2: "http://in5d.com/wp-content/uploads/2015/03/zdhstrrst.jpg"}}
:同様の問題について尋ねるポストをスクロール
$(document).ready(function(){
var iterator = 0;
var count = 1;
setInterval(function(){
count--;
var infiniteLoopPreventor = playlist.length;
while(infiniteLoopPreventor >0 && count == 0){ //make sure no infinite loop and no previous msg is being displayed
var now = new Date();
var currentMsg = playlist[iterator];
for(var timeSet in currentMsg.timeSets){
if(currentMsg.timeSets[timeSet].startDate.getTime()<=now.getTime() &&
currentMsg.timeSets[timeSet].endDate.getTime()>=now.getTime() &&
currentMsg.timeSets[timeSet].days[now.getDay()] == 1 &&
currentMsg.timeSets[timeSet].startTime<=now.getHours() &&
currentMsg.timeSets[timeSet].endTime>=now.getHours()){
//display message
$("#result").load(currentMsg.template);
for(var txt in currentMsg.texts){
$("div#"+txt).html(currentMsg.texts[txt]);
}
for(var img in currentMsg.images){
$("img#"+img).attr("src", currentMsg.images[img]);
}
count = currentMsg.time;
break; //from the for loop which iterates over time sets.
}
}
iterator = (iterator + 1) % playlist.length;
infiniteLoopPreventor--;
}
}, 1000);
});
は、いくつかの提案はどこ製なぜそれが起こっているのかについては適切な解決策は提示されていませんでした。提案された原因は次のとおりです。 - htmlが別のページから読み込まれたため、変更が適用されません。 - 非同期関数です。 - 間隔の問題は、私の問題に適していないclearInterval()を使用して解決できる場合があります。これは、任意の時点で間隔を停止したくないためです。
私はあなたの洞察に感謝します。