1 回答

TA貢獻1900條經驗 獲得超5個贊
您的函數運行正確,問題出在函數代碼本身,而不是在setInterval.
這樣做:
string = string.replace(/_/, char);
你總是試圖更換_角色。從第二次調用函數時起,該字符將不再存在,因為它被第一次調用所替換。
如果您希望最后一個字符不斷變化,您有多種選擇:
string = string.substrstring.replace(/.$/, char);
// or
string = string.substrstring.slice(0, -1) + char;
// or even just
buttons[i].textContent = 'help' + char;
正則表達式.$匹配字符串中最后一個位置的任何字符($匹配字符串的末尾),但它可能是最慢的選項。
工作片段:
const buttons = document.getElementsByTagName('button');
setInterval(charChange, 1000);
function charChange(){
let string;
let chars = ['#', '!', '@', '$', '%', '&', '+', '?'];
for(i = 0; i < buttons.length; i++){
let char = chars[Math.floor(Math.random() * 7)];
buttons[i].textContent = 'help' + char;
}
}
<button id = 'title'>help_</button>
- 1 回答
- 0 關注
- 116 瀏覽
添加回答
舉報