准备好的文档在部分视图中无法正常工作 [英] Document ready is not working correctly in partial view
问题描述
@ Ajax.ActionLink(append smth,AddSmth,new AjaxOptions {UpdateTargetId = smthContainer,InsertionMode.InsertAfter})
< div id =smthContainer>< / div>
我的控制台:
public ActionResult AddSmth()
{
return PartialView(Smth);
}
部分视图:
< input type =textid =dateOfSmth/>
< script type =text / javascript>
$(document).ready(function(){
$('#dateOfSmth')。datepicker();
});
< / script>
问题在于在将部分视图添加到文档之前调用ready函数,因此$('# dateOfSmth')为空。一切工作正常,如果我用InsertionMode.Replace替换InsertionMode.InsertAfter。你有什么想法,为什么它不正确地使用InsertionMode.InsertAfter woking?
编辑:用jQuery追加视图时效果很好:
< a href =javascript:addSmth();>添加Smth< / a>
< script type =text / javascript>
function addSmth(){
$ .get('@ Html.Raw(Url.Action(AddSmth))',null,function(view){
$('#smthContainer ').append(view);
});
}
< / script>
ready 事件被触发一次 - 当DOM完成加载时 - 并且在插入载入AJAX的内容时不会再次触发。如果添加一个准备好事件处理程序,那么它会自动执行。
问题可能是由于两种插入方式( InsertionMode.InsertAfter
和 InsertionMode.Replace
)的差异而导致的
$
$('#dateOfSmth')。datepicker();
在加载完AJAX内容后。
My Main View:
@Ajax.ActionLink("append smth", "AddSmth", new AjaxOptions { UpdateTargetId = "smthContainer", InsertionMode.InsertAfter })
<div id="smthContainer"></div>
My Controller:
public ActionResult AddSmth()
{
return PartialView("Smth");
}
Smth partial view:
<input type="text" id="dateOfSmth" />
<script type="text/javascript">
$(document).ready(function () {
$('#dateOfSmth').datepicker();
});
</script>
The problem is that ready function is called before partial view is added to document, so $('#dateOfSmth') is empty. Everything works fine if I replace InsertionMode.InsertAfter with InsertionMode.Replace. Do you have any idea why is not it woking correctly with InsertionMode.InsertAfter?
EDIT: works well when appending view with jQuery:
<a href="javascript:addSmth();"> Add Smth </a>
<script type="text/javascript">
function addSmth() {
$.get('@Html.Raw(Url.Action("AddSmth"))', null, function (view) {
$('#smthContainer').append(view);
});
}
</script>
The ready
event is fired a single time - when the DOM has finished being loaded - and doesn't fire again when you insert AJAX loaded content. If you add a ready
event handler after that has happened then it will be executed automatically.
The problem is probably caused by a difference in how the two insertion modes - InsertionMode.InsertAfter
and InsertionMode.Replace
- handle <script>
tags in the content.
If you can, simply call your:
$('#dateOfSmth').datepicker();
line after the AJAX content has been loaded.
这篇关于准备好的文档在部分视图中无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!