我試圖在前端用javascript來驗證我的woocommerce chekout form。驗證正確執行,但問題是,每次我把焦點從輸入欄位移開時(我使用了onblur事件),該函式就會被呼叫。 這個div被多次創建。我想讓它只顯示一次,否則它就應該被洗掉。誰能提供一個解決方案? 附上代碼和SS如下。
<h3>我的自定義標題</h3>
<p class="form-row form-row valid-required" >
<input type="billing_first_name">/span>... </p>。
< p class="sp-error-notice"/span> id="sp_billing_first_name_field"/span>> </p>
function myFunction() {
//為名稱
let n = document.getElementById("billing_first_name").value。
// let name_text;.
if ( n.length < 3 || n == ' ' ) {
var n1 = document.getElementById('billing_first_name') 。
n1.insertAdjacentHTML('afterend', '<p class="sp-error-notice" id="sp_billing_first_name_field"> This is a test.</p> ')。
}
else {
var n1 = document.getElementById("sp_billing_first_name_field"/span>) 。
n1.remove()。
}
}
uj5u.com熱心網友回復:
你可以在添加p標簽之前簡單地檢查它是否存在
if(!document.getElementById("sp_billing_first_name_field"/span>)){
n1. insertAdjacentHTML('afterend', '< p class="sp-error-notice" id="sp_billing_first_name_field"> < /p> ')。
}
uj5u.com熱心網友回復:
沒有必要放else,因為元素<p class="sp-error-notice" id="sp_billing_first_name_field">這是一個測驗。</p>從未被創建,它不能remove()它在else條件。此外,沒有必要把 n == ''放在條件中,你的第一個條件已經足夠了,并且滿足了 n == ''。
在這里,我所做的是檢查元素是否被創建,如果已經存在,它會回傳,這將導致重復。
。function myFunction() {
//為名稱
let n = document.getElementById("billing_first_name").value。
// let name_text;.
if(document.getElementById("billing_first_name") 。 nextSibling.nodeName == 'P'){
return。
}
if ( n.length < 3 ) {
var n1 = document.getElementById('billing_first_name') 。
n1.insertAdjacentHTML('afterend', '<p class="sp-error-notice" id="sp_billing_first_name_field"> Error.< /p> ')。
}
}
myFunction()
myFunction()
myFunction()
function myFunction2() {
if(document.getElementById('sp_billing_first_name_field')){
document.getElementById('sp_billing_first_name_field')。 style.display = 'none'.
}
< input type="text"/span> id="billing_first_name" onclick='myFunction2() ' /span>>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" class="snippet-box-edit snippet-box-result" frameborder="0"></iframe>
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/310001.html
標籤:
