與jquery .html()
有幾個問題。下面是一個代碼,它將文本框輸入值從「輸入電子郵件地址」更改爲「」,並且如果它們沒有輸入任何內容,則將「輸入電子郵件地址」放回模糊處。當我更改時,jquery腳本停止工作,然後重新加載要選擇的原始元素
我使用jQuery .html()
與.post()
到PHPMailer的更新與「發送...」「發送成功」,「失敗」等
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#emailaddressinput").focus(function(){
if ($(this).val() == 'Enter email address') {
$(this).val('');
}
});
$("#emailaddressinput").blur(function(){
if (!$.trim($(this).val())) {
$(this).val('Enter email address');
}
});
});
</script>
這裏包含div的代碼是員額的PHPMailer 。成功的迴應是'true'
。但是,當它失敗時,它會使用dotimeout.js延遲3秒,然後使用jquery .html
將原始表單重新放回原位。當它這樣做時,上面的代碼不再起作用。底部是我的原始HTML。
<script src="lib/dotimeout.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#emailbutton').click(function(e) {
e.preventDefault();
var email = $('#emailaddressinput').val();
//write 'sending...' or something
$('#emailinputcontainer').html('Sending, please wait.');
var generated_coupon_id = '2';
var dataString = 'email=' + email + '&generated_coupon_id=' + generated_coupon_id;
$.post('send.php', dataString, function(data){
//do stuff
if(data=='true'){
//say "message sent!"
$('#emailinputcontainer').html('Your coupon has been emailed!');
} else {
//say error
$('#emailinputcontainer').html('There was an error. Please try again.');
$.doTimeout(3000,function() {
$('#emailinputcontainer').html('<input id="emailaddressinput" type="text" value="Enter email address" /><a id="emailbutton" href="#" style="margin: 0 !important;"><span class="buttontext" >Email coupon</span></a>');
});
}
});
});
});
</script>
這裏是形式的原始HTML:
<div id="emailinputcontainer">
<input id="emailaddressinput" type="text" value="Enter email address" /><a id="emailbutton" href="#" style="margin: 0 !important;"><span class="buttontext" >Email coupon</span></a>
</div>
我如何得到我最初的劇本在此頁面的頂部,當電子郵件失敗,我用.html()
重新加載重新工作原創內容。
編輯:其實,我進一步修補,現在.post()
將無法正常工作,這是非常重要的!
感謝您的回答。 '.live('focus',fuction()'等等和東西完美地工作。但是有一個問題 - 爲什麼顯示/隱藏比添加/去除html更好呢? –
有幾個原因:瀏覽器,因爲它不必每次都解析和構建DOM,因爲您不必在兩個位置維護相同的代碼,並且擔心事件不受約束或數據丟失等情況,因此對您更容易。你的上面的代碼電子郵件地址會丟失。)它更容易測試和調試,每當文檔模型更改時,沒有jQuery爲「.live」運行檢查,XSS的向量更少,可以添加動畫,可以快速更改爲浮動錯誤消息等 –
與您的問題無關的更多評論:如果您沒有使用'.html'設置HTML,則應該使用'.text'代替。它更快,並且沒有XSS有風險,另外,你應該逃避你的URL數據:var dataString ='email =' + encodeURIComponent(email)+ ...'您可能還需要驗證客戶端的電子郵件地址以減少無效電子郵件地址的服務器調用。 –