2014-09-25 145 views
0

在我的代码中,我有一个外部脚本,它为我的页面添加了一些元素。这个脚本的document.ready后异步加载:Jquery从外部脚本加载元素

<script src="http://any.com/script.js"></script> 

此脚本包含未来:

$.ajax({ 
     url: '/anyScript', 
     complete: function(){ 
      alert('yo'); // FIRED 
      $('body').append('<div id="xxx" />'); // FIRED 
     } 
    }); 

我需要等到该元素将出现一些样式添加到它

$(function(){ 

    $('body').on('load','#xxx', function(){ 
     $(this).css({ 
      background:'red', 
      width: 100, 
      height: $('#first_el').height() 
     }); 
    }); 
}); 

这不会触发。该怎么办?

更新:http://jsfiddle.net/81ucdoLo/1/

回答

1

此解决方案基于您无法控制外部脚本的假设。因此,建议的解决方案是使用基于时间间隔的解决方案来检查目标元素是否已加载(如果是这样),然后停止时间间隔。

在这种情况下,尝试使用$ .getScript()加载脚本像

jQuery.getScript('http://any.com/script.js', function() { 
    var interval = setInterval(function() { 
     var $el = $('#xxx'); 
     if ($el.length) { 
      clearInterval(interval); 
      $el.css({ 
       background: 'red', 
       width: 100, 
       height: $('#first_el').height() 
      }); 
     } 
    }, 500); 
}) 

演示:Fiddle

+0

是的,我认为唯一一种间隔的方法。这对我来说很有用。谢谢! – 2014-09-25 08:23:13

1

您可以尝试使用ajaxComplete如图所示:

$(document).ajaxComplete(function() { 
    $('#xxx').css({ 
    background:'red', 
    width: 100, 
    height: $('#first_el').height() 
}); 
}); 

Working Demo

+0

不工作。看我的例子在小提琴 – 2014-09-25 08:04:32

+0

@ SergeyKudryashov..see更新的答案plz .. – 2014-09-25 08:10:46

+0

好的解决方案。但它不能帮助我。它可以不是ajax请求,并且xmlHttprequest或者超时或者我可以有很多不同的ajax请求。所以我只需要听什么时候元素会出现 – 2014-09-25 08:20:08

0

这应该等待元素做好准备:

$(function(){ 
    $("#xxx").css('top','123px'); 
    //OR 
    $("#xxx").addClass('topMargin'); 
}); 
+0

已更新。该值由js计算。文档准备好后脚本就会被加载。 – 2014-09-25 07:37:04

0

做财产以后像这样,把你的js称为我们在window.onload中,它会在页面加载后执行doSomthing函数。

window.onload = function() {doSomthing();} 

function doSomthing() 
{ 
    $("#xxx").css('top','123px'); 

} 

或加超时,

setTimeout(doSomthing,1000); 

这将延误通话过程中,经过指定时间后会调用。

如果你试试这个: JSFiddle Demo:

我更新您的演示。