动态表单未提交(jQuery) [英] Dynamic form not submitting (jQuery)

查看:38
本文介绍了动态表单未提交(jQuery)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用PHP,MySQL和&创建一个简单的任务管理器应用程序jQuery的.我正在添加一项功能,该功能将允许用户通过单击新任务"按钮,在文本字段中键入并按Enter键来添加任务.这是我拥有的jQuery:

I'm creating a simple task manager app with PHP, MySQL, & jQuery. I'm adding a feature that will allow users to add a task by clicking a "new task" button, typing into a text field and hitting enter. This is the jQuery I have:

function add_task() {
// Add the "add new task" button
$("<span class='add-new'>Add new item</span>").appendTo(".sub-phase");

// String for the input form
var task_form = '<form class="add-new-task" autocomplete="off"><input type="text" name="new-task" placeholder="Add a new item..." /></form>';

// Display form on button click
$('.add-new').click(function() {
    $(task_form).appendTo($(this).parent());
});

// Post results
$('.add-new-task').submit(function(){
var new_task = $('.add-new-task input[name=new-task]').val();

if(new_task != ''){
$.post('includes/add-tasks.php', { task: new_task }, function( data ) {
    $('.add-new-task input[name=new-task]').val('');
    $(data).appendTo('.task-list').hide().fadeIn();
        });
}
return false;
});
}

如果我在index.php文件中对表格进行了硬编码,则此功能将按预期工作.但是,如果表单是像我在此处那样在jQuery中创建的,则提交时不会发生任何事情.我已经搜索过了,但是找不到能解决问题的解决方案.

If I have the form hardcoded in the index.php file, this functionality works as expected. But if the form is created in jQuery like I have it here, then nothing happens on submit. I've searched around but haven't been able to find a solution that works.

任何建议都将不胜感激!谢谢.

Any advice is much appreciated! Thank you.

推荐答案

问题是您没有委派事件.您已经在页面加载时设置了一个提交处理程序,但没有为动态创建的元素设置

The issue is that you're not delegating the event. You've setup a submit handler on page load, but not for dynamically created elements.

更改:

$('.add-new-task').submit(function(){

收件人:

$(document).on('submit', '.add-new-task', function(){

现在,事件处理程序已绑定到文档,并且将使用 .add-new-task 触发页面上的任何元素,而不管它是否是动态创建的.

Now the event handler is bound to the document and will trigger for any element on the page with .add-new-task regardless of whether or not it was dynamically created.

另外,值得注意的是,应尽可能避免绑定到 document ,而应绑定到最近的静态父元素.

Also, of note, you should avoid binding to document where possible, and instead, should bind to the closest static parent element.

这篇关于动态表单未提交(jQuery)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆