2013-08-03 38 views
0

我只是試圖讓一個提交的表單, 的動作鏈接,但點擊提交警報未定義無法獲得點擊的形式

$(document).on("submit","form",function(e){ 
    e.preventDefault(); 
    if($(this).children("input[type=submit]").hasClass("load") && $(this).children("input[type=submit]").hasClass("last-button")) 
    { 
     setTimeout(function(){ 
     alert($(this).attr("action")); 
     //  $.post($(this).attr('action') , $(this).serialize() , function(data){ 
     // $(".wholepage").html(data); 
     // }); 
     },400); 
    } 
}); 

HTML

<div class="well login"> 
    <form id="reg" action="parts/background/regProcess.php" method="post"> 
     <input placeholder="Choose an username" type="text" name="user"><br/><br/> 
     <input placeholder="Choose a password" type="password" name="pass1"><br/><br/> 
     <input placeholder="Input the password again" type="password" name="pass2"><br/><br/> 
     <input placeholder="Enter your E-mail address" type="text" name="email"><br/> 
     <input type="submit" class="last-button load" value="SUBMIT"> 
    </form> 
</div> 
+0

這是一個[CodePen](http://codepen.io/anon/pen/GHapf)。 – FakeRainBrigand

回答

1

你需要的動作鏈接在您的超時功能之前存儲$(this)

$(document).on("submit","form",function(e){ 
    e.preventDefault(); 
    var $this = $(this); 
    if($(this).children("input[type=submit]").hasClass("load") && $(this).children("input[type=submit]").hasClass("last-button")) 
    { 
    setTimeout(function(){ 
     var relPath = $this.attr("action"); 
     var absPath = $this.prop("action"); 
     alert(relPath); 
     //  $.post($(this).attr('action') , $(this).serialize() , function(data){ 
     // $(".wholepage").html(data); 
     // }); 
    },400); 
    } 
}); 

這是小提琴:http://jsfiddle.net/vMbHS/

+0

FakeRainBrigand對'prop()'做了評論,我總是忘記了,所以我加入了它。評論似乎已經消失了。 –

+0

它工作感謝:-) – Ario

1

另一種解決方案是使用bind綁定this

$(document).on("submit","form",function(e){ 
    e.preventDefault(); 
    if($(this).children("input[type=submit]").hasClass("load") && $(this).children("input[type=submit]").hasClass("last-button")) 
    { 
     setTimeout((function(){ 
     alert($(this).attr("action")); 
     //  $.post($(this).attr('action') , $(this).serialize() , function(data){ 
     // $(".wholepage").html(data); 
     // }); 
     }).bind(this),400); 
    } 
}); 

這將創建一個更易維護的代碼,因爲函數對父函數的變量鬆散。