简体   繁体   English

jQuery .each与ajax加载内容的用法

[英]jQuery .each usage with ajax loaded content

I have the following functions, the func resizeInputText works fine. 我具有以下功能,func resizeInputText工作正常。 Basically I would like to call resizeAll when my application has successfully loaded data via ajax. 基本上,当我的应用程序通过Ajax成功加载数据时,我想调用resizeAll。

As the content is pulled after the page load I have attempted to wrap my each code in the .on event. 由于在页面加载之后提取内容,因此我尝试将每个代码包装在.on事件中。

It's not working, does anyone know how to do this or how to call .each with ajax loaded content? 它不起作用,有人知道如何执行此操作或如何使用ajax加载的内容调用.each吗?

Thanks as always! 一如既往的感谢!

function resizeInputText(obj) {
var boxWidth = ($(obj).val().length * 7) + 1;
    if (boxWidth <= 30) {
        var boxWidth = 30;
    } else if (boxWidth >= 250) {
        var boxWidth = 250;
    }
$(obj).css({width:boxWidth});
}

function resizeAll() {
$("#right-content").on(function () {
    $("input:text").each(function () {
        resizeInputText(this);
    });
});
}

The .on method in your resizeAll doesn't have an event which it executes the function for. 您的resizeAll中的.on方法没有为其执行功能的事件。 You can see the various usages on the documentation page , but basically you need to tell it which event to listen for, and what to do when that event is raised. 您可以在文档页面上看到各种用法,但是基本上您需要告诉它要监听哪个事件,以及在引发该事件时该怎么做。 Ajax broadcasts some events which you can bind to using the .on method, and in this case the 'ajaxSuccess' might be the appropriate one for you. Ajax广播一些事件,您可以使用.on方法绑定到这些事件,在这种情况下,“ ajaxSuccess”可能是适合您的事件。

However, the better approach for you would be to pass in resizeAll as the callback for your ajax method, which will be executed on a successful completion of the ajaxCall. 但是,对您来说更好的方法是将resizeAll作为ajax方法的回调传递,该方法将在resizeAll成功完成后执行。 The jQuery ajax syntax allows you to do this by including the option success: resizeAll . jQuery ajax语法允许您通过包含success: resizeAll选项success: resizeAll来实现此success: resizeAll You would modify your resizeAll to look like this in that case: 在这种情况下,您可以将resizeAll修改为如下所示:

function resizeAll() {
    $("input:text").each(function () {
        resizeInputText(this);
    });
}

您可以简单地在AJAX请求的success回调中调用该函数。

As ThiefMaster said you can do something like this : 正如ThiefMaster所说,您可以执行以下操作:

$.ajax({  
url : "requested url",
data : { "data to be send "},
success : function(data) {
   $.each(data, function(index,value) {

     //your code goes here
  });
}
}); 

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

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