![](/img/trans.png)
[英]Replace div contents with jQuery on form submit within PHP loop
[英]Replace contents of <div> in a loop while waiting
我很難弄清我的問題,甚至找不到解決方案,這使我相信我可能會走錯了方向。
在cshtml
頁面上,我具有一個與按鈕單擊相關聯的ajax
函數。 路由返回到我的控制器,並且json字符串數組返回給客戶端。
在頁面本身上,我定義了<pre id="replaceMe">***</pre>
。 我試圖通過做$("#replaceMe").replaceWith('<pre id="replaceMe">' + data[i] + '</pre>');
的json數組進行迭代$("#replaceMe").replaceWith('<pre id="replaceMe">' + data[i] + '</pre>');
從技術上講,這是可行的,但僅在可以看到最新更新的意義上。 我也可以直接轉到數組的最后一個元素。
我嘗試使用setTimeout
無效,沒有更改,然后突然顯示了最后一個元素。 我發現一些類似函數的sleep
,它們模仿相同的基本行為,而所有結果都相似。 我確實看到一些關於async sleep
建議,但是我的瀏覽器似乎都不喜歡異步並給我一個關於丟失的錯誤;
。
然后我以為我可以做類似的事情
function updateSection(data) {
for (var i = 0; i < data.length; i++){
var section = $("#replaceMe");
section.fadeOut(500);
section.replaceWith('<pre id="replaceMe">' + data[i] + '</pre>');
section.fadeIn(500);
}
}
然而,這具有相同的最終結果。 沒有明顯的變化,然后突然變成了數組中的最后一個元素。
我顯然正在解決這個錯誤,否則我會很容易地找到一個示例,那么我應該怎么做呢?
為了澄清和總結,我想用數組中包含的文本替換<pre></pre>
的內容。 我希望每個迭代都足夠長的可見時間,以便人類可以看到它並觀察變化(〜1000ms),然后再進行下一個迭代。
例如,如果數組包含"Tom", "Dick", "Harry"
,那么我希望頁面具有
<pre id="replaceMe">Tom</pre>
1秒鍾,然后將該元素替換為
<pre id="replaceMe">Dick</pre>
1秒鍾,然后將該元素替換為
<pre id="replaceMe">Harry</pre>
我不在找
<pre id="replaceMe">Tom</pre>
<pre id="replaceMe">Dick</pre>
<pre id="replaceMe">Harry</pre>
for
循環中的setTimeout
在for循環執行完成后運行。 因此,您總是看到最后一個值。 要解決此問題,可以使用提供回調函數的$.each
方法或使用立即調用的函數表達式。
更詳細的信息: https : //codehandbook.org/understanding-settimeout-inside-for-loop-in-javascript/
var data=[]; for(var i=0; i<10; i++){ data.push(i+' lorem ipsum doloret'); } $.each(data, function(i, el){ setTimeout(function(){ $("#replaceMe").replaceWith('<pre id="replaceMe">' + data[i] + '</pre>'); },500 + ( i * 1000 )); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <pre id="replaceMe">***</pre>
您可以使用setInterval函數做到這一點:
var words = ['interating', 'and', 'replacing', 'text'];
var replace = document.querySelector('#replace');
var count = 0;
function replaceText() {
replace.innerHTML = words[count];
if(count === words.length - 1)
count = 0;
else
count++;
}
setInterval(replaceText, 1000);
更新:不需要替換所有元素,可以使用屬性innerText替換僅內容。
//pass in the data to loop over, and the index to show function updateSection(data, index) { //get a reference to the section var $section = $('#replaceMe'); //fade out the section over 500 milliseconds, then perform callback on finish $section.fadeOut(500, () => { //change the text $section.text(data[index]); //fade in the section over 500 milliseconds, and then advance the index //use modulus to reset the index to 0 when it reaches beyond the array $section.fadeIn(500, () => updateSection(data, ++index % data.length)); }); } updateSection(['Tom', 'Dick', 'Harry'], 0);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="replaceMe">***</div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.