前言
我們?cè)谇岸丝倳?huì)遇到重復(fù)點(diǎn)擊的問題,由于網(wǎng)絡(luò)的原因,用戶不能及時(shí)得到反饋,就很可能會(huì)選擇再點(diǎn)擊一次,
所以這個(gè)時(shí)候就會(huì)向后端發(fā)送兩次重復(fù)的請(qǐng)求,這樣就很可能會(huì)導(dǎo)致嚴(yán)重的問題,尤其是在發(fā) post的時(shí)候,就可能會(huì)增加兩條重復(fù)的數(shù)據(jù)。
之前我一般遇到這種情況都會(huì)在 js 的請(qǐng)求前做一個(gè) canRequest 變量,由于請(qǐng)求是異步的,所以在請(qǐng)求開始后我就會(huì)將該變量設(shè)置為 false, 當(dāng)請(qǐng)求結(jié)束后,無論成功還是失敗都要將該變量設(shè)置為 true, 簡(jiǎn)單代碼如下:
var canRequest = truefunction postData () { if (!canRequest) return fetch(url) .then(res => { canRequest = true }) .catch(e => { canRequest = true }) canRequest = false}
這樣做并沒有什么毛病,不過考慮到一般點(diǎn)擊后還需要將按鈕置灰,所以我找到了個(gè)從 css 層面上就阻止重復(fù)點(diǎn)擊的方式。
下面是個(gè)獲取短信驗(yàn)證碼的示例:
<div id="count">獲取驗(yàn)證碼</div>
body { display: flex; height: 100vh;}#count { margin: auto; padding: 10px; width: 100px; border: 1px solid; text-align: center; cursor: pointer; border-radius: 4px;}.disable { pointer-events: none; color: #666;}
const count = document.getElementById('count')const tip = count.textContentcount.onclick = e => { console.log(111) count.classList.add('disable') count.textContent = 10 var id = setInterval(() => { count.textContent-- if (count.textContent <= 0) { count.classList.remove('disable') count.textContent = tip clearInterval(id) } }, 1000)}
總結(jié)
以上就是這篇文章的全部?jī)?nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作能帶來一定的幫助,如果有疑問大家可以留言交流,謝謝大家對(duì)VeVb武林網(wǎng)的支持。
新聞熱點(diǎn)
疑難解答
圖片精選