2014-09-25 107 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:

我更新您的演示。