JQuery $('form').serialize() 在 $('div.container').load() 之后不工作

JQuery $('form').serialize() not working after $('div.container').load()

我有一个带有 div 的页面,该页面通过 AJAX 调用更新,如下所示:

<body>
    <div id="container">
        <div id="newinfo">
            <form id="selectform">
                Your name:<br>
                <input type="text" name="firstname"><br>
            </form> 
        </div>
    </div>
    <script>
        function reload_container() {
            $('#container').load('url/to/ajax/update');
            console.log($('#selectform').serialize());
        }
    </script>
</body>

加载响应相同(包括表单 ID),但内容不同。

如果我从 Firefox 的调试控制台 运行 reload_container(); 但是 serialize() 函数是空的,但是 $('#selectform') 确实被定义了。

但是我需要表格的内容。我不知道为什么 $('#selectform') 选择器在重新加载后可以工作,但 serialize() 不能。非常感谢任何帮助。

请注意,表单的输入确实包含姓名标签。 jQuery serialize not working 不相关。

更新:绑定到容器中元素的事件在 load() 之后也不起作用。例如。 $('#newinfo').click(function(){alert('hi!'}); 在正文加载脚本中。但是 jQuery .live() vs .on() method for adding a click event after loading dynamic html

解决了这个问题

您应该在加载完成处理程序中执行您的代码。

$('#container').load('url/to/ajax/update', function() {
  console.log($('#selectform').serialize());
});

在此处查看示例 http://api.jquery.com/load/

这似乎工作正常。您的 ajax 处理程序可能有问题。希望这个例子对你有帮助。 还在输入元素上使用委托 input 事件制作了一个示例。

如果您需要帮助,请提供您的 ajax 处理程序。

//define delegate event so it triggers after inserting new elements (with ajax) too.
$('#newinfo').on('input', 'input[name=firstname]', function(){
  console.log($(this).val());
});

//attach the reload_container function to the button for testing purpose
$('#reload').on('click', reload_container);

//This function mimics the result of your ajax request assuming you do something like this. It updates the form with a new form and run the serialize function on it.
function reload_container() {
  var ajaxResultMimic = '<form id="selectform">Your name:<br><input type="text" name="firstname" value="updated"><br></form>';
  $('#newinfo').html(ajaxResultMimic);
  console.log($('#selectform').serialize());
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
    <button id="reload">reload</button>
    <div id="container">
        <div id="newinfo">
            <form id="selectform">
                Your name:<br>
                <input type="text" name="firstname"><br>
            </form> 
        </div>
    </div>
</body>