我試圖防止頁面重新加載或提交時,用戶單擊取消選項。我查看了周圍的stackoverflow,並且對於我遇到的問題具有相同的語法,但我嘗試了類似的方式,並且它仍然提交併重新加載取消選項上的頁面。我如何防止它做任何事情並按原樣取消頁面?如何防止頁面重新加載或刷新取消選項?
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>
仍然沒有工作。以下是完整的代碼:http://jsfiddle.net/LGd2f/2/ – TheAmazingKnight
你確定嗎?你似乎沒有在loooong小提琴中使用onsubmit處理程序:)這裏是一個更新,你可以看到自己,如果頁面重新加載或不 - - http://jsfiddle.net/BS55A/ – davidkonrad
謝謝,終於明白了!看起來'submitBtn.addEventListener'不能識別該事件,因爲它是一個按鈕,僅此而已。反對使用'frm.onsubmit'並在表單提交的事件中使用該值。謝謝,我會牢記這一點! – TheAmazingKnight