![](/img/trans.png)
[英]How to execute a javascript code strictly after the complete page has been loaded?
[英]How to execute if statement after page has been loaded?
在此處查看其運行情況: http : //jsbin.com/relamiqeru/1/
我正在嘗試這樣做,以便如果用戶在優惠券代碼字段中輸入“ idh4”,則我的“ booyah” div會被提供的html所填充。
我感覺到的問題是,僅在加載頁面時才執行javascript,因此即使將idh4輸入到字段中,它也不會對其進行檢查。 也許if語句在這種情況下不適合使用?
根據要求,這是jsbin代碼:
<div id="booyah"></div>
<form action="" method="POST">
Coupon Code?<input id="couponcode" type="text" name="coupon code" value="idh4"><br>
<input type="submit">
</form>
$("#couponcode").change(function(){
if ($("#couponcode").val() === 'idh4') {
console.log('it got called');
$( "#booyah" ).html("<p>That code gets you free snappie stickers!</p>");
}
});
我不確定這是否是您想要的,但是無論如何您都可以看一下:
$(document).ready(function(){
$("#booyahInput").on('keyup', function(){
if ($(this).val() == 'idh4') {
console.log('it got called');
$( "#booyah" ).html("<p>That code gets you free snappie stickers!</p>");
}
});
});
這里的問題是您在文本框上使用了change
事件:
$("#couponcode").change
在文本框上, change
失去了焦點。 因此,輸入優惠券后,用戶必須離開該字段。
而是嘗試使用input
, keyup
, keypress
事件進行即時響應。
$("#couponcode").on('input', function(){
//
});
如果要在提交時觸發,則必須添加一個函數在提交時觸發,如果要在提交的字段中更改文本時觸發,則需要聽事件。 了解事件監聽器是了解javascript的關鍵。
這里有2個參考:提交:
http://www.javascript-coder.com/html-form/html-form-tutorial-p1.phtml
聽眾:
您遇到的問題是,提交表單后,頁面正在重新加載。 為此,您需要通過AJAX提交表單,並防止頁面刷新。 但是使用您提供的代碼尚不清楚是否正在執行此操作。
$("#myform").on("submit", function(e) {
e.preventDefault();
if ($("#couponcode").val() === 'idh4') {
console.log('it got called');
$("#booyah").html("<p>That code gets you free snappie stickers!</p>");
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.