问题
In ASP.NET MVC, what is the preferred pattern for running Javascript on a partial view that is loaded via Ajax?
For example, suppose you need to wire up some click events in your partial view.
Of course, putting something like this in the partial view would not work, because the document ready event won't fire after the partial view is Ajax loaded.
<script type="text/javascript">
$(function() {
$("a.foo").click(function() {
foo();
return false;
});
});
</script>
I suppose something like this might work, but is it safe?
<script type="text/javascript">
$("a.foo").click(function() {
foo();
return false;
});
</script>
The pattern I have been using has been to run any Javascript from my parent view after loading the partial, like this:
$.get(url, function(html) {
$("#partialDiv").html(html);
// Now that the partial has loaded...
RegisterClicks();
});
But I've been working through this example, and noticed that they simply put their click registering code inline in the partial view.
Is this a generally safe pattern to adopt? How can I be sure that the DOM for the partial view has finished loading before my script runs?
回答1:
The jQuery .on() function should do the trick, shouldn't it? It should work for dynamically added content.
Have this available as part of the full content
<script type="text/javascript">
$(function() {
$("#partialContent").on("click", "a.foo", function() {
foo();
return false;
});
});
</script>
<div id="partialContent">
<a href="#" class="foo">Link 1</a>
<a href="#" class="foo">Link 2</a>
<!-- More dynamic content -->
</div>
回答2:
Scripts are not loaded on Partial view via partial view loaded by ajax in Asp.net MVc
<div class="modal fade" id="myEditCourseModal" role="dialog">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title text-center">Update Data</h4>
</div>
<div class="modal-body" id="CourseEditPreview">
@Html.Action("CourseUpdatePartial", "AdminCourse")
</div>
</div>
</div>
</div>
<script type="text/javascript">
function OpenCourseEdit(currentId) {
$.ajax({
type: "Get",
url: '@Url.Action("CourseUpdatePartial", "AdminCourse")',
cache: false,
Async: true,
contentType: 'application/html;charset=utf-8',
dataType: "html",
data: { CourseID: currentId },
success: function (data) {
var content = $('#CourseEditPreview').html(data);
eval(content);
$('#myEditCourseModal').modal('show');
},
error: function (error) {
$("#LoadingPanel").css("display", "block");
$('#CourseEditPreview').html("");
}
})
}
</script>
来源:https://stackoverflow.com/questions/14838789/how-should-javascript-in-an-ajax-loaded-partial-view-be-handled