ASP.NET MVC 3 Ajax 表单:更新 DOM 后运行 JavaScript
我有一个 MVC3 Web 项目,其中包含非常简单的搜索表单。它使用不显眼的 AJAX 来返回包含表格形式结果的 HTML 片段,并替换现有表格。我的问题是,我想在表格上使用DataTables jQuery插件来进行排序、分页等。但是我无法找出调用表格上插件初始化代码的正确方法。
到目前为止我所拥有的是这个(this.Html.Script 只是我编写的用于自动生成脚本标签的扩展方法):
Search.cshtml:
@section ScriptSection
{
@this.Html.Script("libs/jquery.unobtrusive-ajax.min.js")
@this.Html.Script("libs/jquery.validate.js")
@this.Html.Script("libs/jquery.validate.unobtrusive.js")
@this.Html.Script("libs/jquery.dataTables.js")
<script type="text/javascript">
function initTable() {
$("table.datatable").dataTable();
}
</script>
}
@using ( this.Ajax.BeginForm("DoSearch", "Case", new AjaxOptions
{
HttpMethod = "GET",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "results",
OnSuccess = "initTable"
}) )
{
<button type="submit" name="SearchType" value="date">Search</button>
}
<table id="results" class="datatable">
</table>
问题是 initTable() 似乎是在我想要的表实际上在 DOM 中之前调用。结果是结果表完全无样式地插入到页面中,并且没有启用任何数据表功能。
我这样做是否正确,或者是否有其他方法可以在 DOM 更新后触发 jQuery 运行?
I have an MVC3 web project that includes very simple search form. It uses unobtrusive AJAX to bring back an HTML fragment containing the results in table form, and replaces an existing table. My problem is, I want to use the DataTables jQuery plug-in on the table to get sorting, paging, etc. But I cannot figure out the correct way to call the plug-in initialization code on the table.
What I have so far is this (this.Html.Script is just an extension method I wrote to auto-gen the script tags):
Search.cshtml:
@section ScriptSection
{
@this.Html.Script("libs/jquery.unobtrusive-ajax.min.js")
@this.Html.Script("libs/jquery.validate.js")
@this.Html.Script("libs/jquery.validate.unobtrusive.js")
@this.Html.Script("libs/jquery.dataTables.js")
<script type="text/javascript">
function initTable() {
$("table.datatable").dataTable();
}
</script>
}
@using ( this.Ajax.BeginForm("DoSearch", "Case", new AjaxOptions
{
HttpMethod = "GET",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "results",
OnSuccess = "initTable"
}) )
{
<button type="submit" name="SearchType" value="date">Search</button>
}
<table id="results" class="datatable">
</table>
The problem is that initTable() appears to be called before the table I want is actually in the DOM. The outcome is that the results table is inserted into the page completely unstyled and with none of the dataTable features enabled.
Am I doing this right, or is there a different way to trigger the jQuery to run once the DOM has been updated?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
将你的代码放入:
看看这是否适合你 - 然后 DOM 应该被完全加载。
put your code in:
and see if that does it for you - the DOM should be completely loaded then.
哎呀,愚蠢的错误。 jQuery DataTables 需要标签,但我没有使用。抱歉产生噪音。
Bleh, stupid mistake. jQuery DataTables needs the tags, which I wasn't using. Sorry for the noise.