【问题标题】:AJAX/Javascript In a Form and then submit itAJAX/Javascript 在表单中然后提交
【发布时间】:2012-02-19 16:04:11
【问题描述】:

我是一名 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添加,它不会发现表单存在。

我应该如何解决这个问题?

【问题讨论】:

  • 除了 Rory McCrossan 所说的,帮自己一个忙,使用客户端 HTML 模板,如 Handlebars,而不是一点一点地构建 HTML 字符串,然后用 jQuery 操作它来更改你的数据需要改变。

标签: javascript jquery ajax forms jqtouch


【解决方案1】:

使用快捷事件处理程序(例如 submit()click())仅适用于页面加载时放置在 DOM 中的元素。

对于动态添加的元素,您需要使用delegate(),或者对于jQuery 1.7+ 使用on()。试试这个:

$('#search-results').delegate('#product-form', 'submit', function() {
    // rest of your code
});

jQ 1.7+

$('#search-results').on('submit', '#product-form', function() {
    // rest of your code
});

【讨论】:

  • 以上也可以使用jQuery的.live()方法完成,但由于此处描述的问题不建议这样做:api.jquery.com/live
  • @Vivek live() 在任何情况下都不应再使用。甚至在它被弃用之前,它的使用就被delegate() 取代,因为它的性能要好得多。
  • @RoryMcCrossan 嗯!谢谢你的澄清,很高兴有你在身边:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多