简体   繁体   English

jQuery-在Ajax调用后使用长度查找div

[英]jQuery - using length to find div after ajax call

UPDATE: 更新:

The issue was the div was in a div that was hidden, when divs are hidden length, offset(), position() don't work properly. 问题是div位于隐藏的div中,当div处于隐藏长度时,offset(),position()无法正常工作。

// Original Post below. //下面的原始帖子。


This should be simple. 这应该很简单。

I'm trying to test if a div exsists on the page after an ajax .html() output 我正在尝试测试ajax .html()输出后页面上是否存在div

if($('#'+mydiv).length != 1) {
   // do stuff
}

there is only one problem, if the div your searching for is not there when (document).ready fires then .length doesn't see it. 只有一个问题,如果(document).ready触发时,如果您要搜索的div不存在,则.length看不到它。

You could just use the size() method 您可以只使用size()方法

if($('#'+mydiv).size() != 1) {
   // do stuff
}

This recounts the number of matching elements in the DOM. 这将重新计算DOM中匹配元素的数量。

If you are performing an async request, which I assume you are ( async:true in JQuery) then you should be using size() in the success callback of your function, after the content has been added. 如果您正在执行一个异步请求(我假设您是异步请求)(在JQuery中为async:true ),那么在添加内容之后,应该在函数的成功回调中使用size()。

   $.ajax({
        url: requestUrl,
        type: 'POST',
        dataType: 'json',
        data: {},
        success: function(response) {
                $('#container').html(response.data);
                if($('someSearch').size() > 0)
                    alert('exists');
            }
    });

I run into the exact same problem with the ticker after page content has been loaded using ajax - my solution was to use the livequery plugin : http://github.com/brandonaaron/livequery/downloads . 在使用ajax加载页面内容之后,我遇到了与股票行情完全相同的问题-我的解决方案是使用livequery插件: http : //github.com/brandonaaron/livequery/downloads I then use it in the following way: 然后,按以下方式使用它:

$('.ticker').livequery(function() {     
    if ($(this).length > 0) {
        var thisObj = $(this);
        if (thisObj.length > 1) {
            jQuery.each(thisObj, function() {                   
                systemObject.tickerExe($(this));
            });
        } else {    
            systemObject.tickerExe(thisObj);
        }
    }
});

I hope this helps. 我希望这有帮助。

You could use something like: 您可以使用类似:

$('#loader').load('url', {variable1:var1}, function () { 
    if($('#'+mydiv).length != 1) {
       // do stuff
    }
});

That should look for anything loaded after your load call is finished loading. 在您的加载调用完成加载之后,它应该查找已加载的任何内容。

Ensure your div isn't hidden when checking length. 检查长度时,请确保您的div不隐藏。 Usually, hidden div's can cause lots of problems. 通常,隐藏的div会导致很多问题。

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

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