[英]AJAX/Javascript In a Form and then submit it
我是php開發人員,開始越來越沉重地使用ajax,遇到了一個我不確定如何解決的問題。
我正在像這樣動態創建表單:
function addSearchResult(label, tz) {
var html = '';
html += '<div>'
html += '<form id="product-form" >';
html += '<div class="clock">'
html += '<div class="hour"></div>'
html += '<div class="min"></div>'
html += '<div class="sec"></div>'
html += '<input type="text" id="label" name="Label" placeholder="Label">'
html += '</div>'
html += '<div class="city">GMT</div>'
html += '<a href="#" class="whiteButton submit" id="view-product-button" >View</a>'
html += '</form>'
html += '</div>'
var insert = $(html);
$('#search-results').append(insert.data('tz_offset', tz).find('.city').html(label).end());
}
我正在閱讀這樣的表單結果:
$('#product-form').submit(function() {
alert('OK');
addProduct('Test Value', 'Test Produlct');
$('input').blur();
$('#add .cancel').click();
this.reset();
return false;
});
問題是,它不起作用。 如果我將表單直接放在html中,則效果很好。 但是通過ajax添加它,將不會發現該表單存在。
我應該如何解決這個問題?
使用快捷方式事件處理程序(例如submit()
或click()
)僅適用於頁面加載時放置在DOM中的元素。
對於動態添加的元素,您需要對jQuery 1.7+使用delegate()
或on()
。 嘗試這個:
<jQ 1.7
$('#search-results').delegate('#product-form', 'submit', function() {
// rest of your code
});
智商1.7+
$('#search-results').on('submit', '#product-form', function() {
// rest of your code
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.