簡體   English   中英

如何防止頁面在“取消”選項上重新加載或刷新?

[英]How to prevent the page from reloading or refreshing on cancel option?

我試圖阻止頁面在用戶單擊“取消”選項時重新加載或提交。 我環顧了stackoverflow,並針對遇到的問題使用了相同的語法,但是我嘗試了類似的操作,但它仍會提交並在cancel選項中重新加載頁面。 如何防止其執行任何操作並使頁面保持原樣處於取消狀態?

JavaScript代碼:

// create an input element
var frm = document.getElementById("result");
var submitBtn = document.createElement("input");
submitBtn.type = "submit";
submitBtn.value = "Confirm Purchase";
frm.appendChild(submitBtn);
submitBtn.addEventListener('click', function()
{
    // confirm the data
    var submitQ = confirm('Are you sure you want to submit your DSLR selections?');
    if(submitQ)
    {
    alert('Your query has been submitted! Have a great day! :)');
    }
    else document.getElementById("result").onsubmit = false; // prevent the page from refreshing on Cancel option
});

HTML代碼:

<form id="result" onsubmit="true">
    <!--Store User Selection Text Node Element Here-->
        <!--<p>Your DSLR budget range selected was:</p>
    <p>The DSLR brand you selected was:</p>
    <p>The type of photography you selected was:</p>
    <p>The type of lenses you selected was:</p>
    <input type="submit" value="Confirm Purchase"/>
    <input type="button" value="Reset All"/>-->
</form>

更改事件處理程序以解決表單onsubmit事件,而不是提交按鈕click事件。 如果用戶取消,則返回false:

frm.onsubmit = function(){
    // confirm the data
    var submitQ = confirm('Are you sure you want to submit your DSLR selections?');
    if(submitQ)
    {
    alert('Your query has been submitted! Have a great day! :)');
    } else {
       // prevent the page from refreshing on Cancel option
       return false;
    }
};

看到小提琴-> http://jsfiddle.net/LGd2f/

也許您應該嘗試將事件附加到表單提交事件上,而不是單擊按鈕,然后返回falsetrue

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM