简体   繁体   English

部分加载时运行Javascript / Jquery

[英]Run Javascript/Jquery when partial loads

All the examples/answers seem to show running a partial's javascript when the page loads. 页面加载时,所有示例/答案似乎都显示在运行部分javascript。

This partial does not load when the page loads... It is loaded later on a button click using AJAX. 页面加载时不加载此部分...稍后使用AJAX单击按钮时加载。

Ive tried my JS 我试过我的JS

inside: 内:

$(document).ready(function () {

AND : 与:

$(function(){

AND : 与:

By itself 通过它自己

First doesnt trigger at all. 首先根本不会触发。 Second and 3rd seem to trigger on second page load. 第二页和第三页似乎在第二页加载时触发。 I assume because the div that my js affects will exist. 我认为是因为我的js影响的div将存在。 So how do I make it run when Partial loads .. 那么,如何使它在部分加载时运行..

$(document).ready(function () {
    ...
});

Will trigger when the page is loaded (more concretely $(document).ready is wired to the document.DOMContentLoaded or window.loaded event) but because you load Partial with ajax, the page load event is already fired when the Partial is loaded. 将在页面加载时触发(更具体地说,$(document).ready连接到document.DOMContentLoaded或window.loaded事件),但是由于您使用ajax加载Partial,因此在加载Partial时已经触发了页面加载事件。

If you use jQuery to load partial page via ajax I would suggest you to call your function from the 如果您使用jQuery通过Ajax加载部分页面,建议您从

$ajax(...
}).done(function ( data ) {
    yourFunction();
});

Or if you use the AjaxHelper class (eg with razor @Ajax.ActionLink(... )) then use its AjaxOption's OnSuccess or OnComplete property to wire in your javascript function. 或者,如果您使用AjaxHelper类(例如,使用剃刀@ Ajax.ActionLink(...)),则使用其AjaxOption的OnSuccess或OnComplete属性连接您的javascript函数。 Like the following way: 就像下面这样:

@Ajax.ActionLink("Load partial", "MyPartialAction", new AjaxOptions
{
    UpdateTargetId="partialContainer",
    OnSuccess="partialLoaded"
}

This code will load the Partial which is returned from the MyPartialAction action into the markup which has "partialContainer" id and after the Partial is loaded your javascript function named partialLoaded. 这段代码会将MyPartialAction操作返回的Partial加载到具有“ partialContainer” ID的标记中,并在加载Partial之后,将您的JavaScript函数命名为partialLoaded。

If you want to make it run when a partial loads, do it in the callback of whatever is issuing the request for the partial. 如果要使其在部分加载时运行,请在发出部分请求的回调中进行操作。 If this request issuer is Jquery, it would be something like the following: 如果此请求发布者是Jquery,则它将类似于以下内容:

$.get(url, function (result) {
    // Do whatever you want here in the success callback.
});

If you are doing something with an MVC helper method such as Ajax.ActionLink, you can specify a jquery function to call upon response 如果您正在使用MVC帮助程序方法(例如Ajax.ActionLink)进行操作,则可以指定一个jquery函数以响应时调用

@Ajax.ActionLink("NameOfLink", "ControllerAction", new AjaxOptions
{
    HttpMethod = "GET",
    OnSuccess = "javascriptFunction(data)"
})

function javascriptFunction(data) {
    // Do whatever you want
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM