2013-04-23 58 views
1

我正在使用$.get()函數從我的網站中提取一些數據。一切都很好,但是在其中一頁上,我需要提取的信息是動態創建的,然後插入到<div>標籤中。在jquery中使用get函數時腳本沒有運行

因此,在<script>標籤中,運行一個函數,然後將數據插入<div id="infoContainer"></div>。我需要從#infoContainer獲得信息,但是當我嘗試在$.get()函數中這樣做時,它只是說它是空的。我發現這是因爲<script>標籤沒有運行。有沒有另一種方法來做到這一點?

編輯:我正在爲我的網站製作一個PhoneGap應用程序,使用jQuery來移動內容,所以對於移動設備來說它更簡化了。

這是我的網頁上的代碼:

$(document).ready(function() { 
    var embedTag = document.createElement("embed"); 
    var infoContainer = document.getElementById("infoContainer"); 

    if (infoContainer != null) { 
     embedTag.setAttribute("height", "139"); 
     embedTag.setAttribute("width", "356");...other attributes 

     infoContainer.appendChild(embedTag); 
    }); 
}); 

正如你所看到的,它把內容放到#infoContainer標籤。但是,當我嘗試通過get函數從該標記提取信息時,它將其顯示爲空。我已經完成了相同的操作,以提取標題並且效果很好。我可以收集的是腳本標籤沒有觸發。

+4

你到底在做什麼?我們可以看到一些小代碼嗎? – SomeShinyObject 2013-04-23 04:09:01

+0

我們不能在沒有看到有問題的代碼的情況下告訴你代碼有什麼問題。 – jfriend00 2013-04-23 04:13:12

+1

'$ .get()'只是將返回的數據放在一個字符串中,它不會執行它。即使你告訴它它是HTML,它也不知道你打算如何處理它。也許你真的需要'$ .load' – Barmar 2013-04-23 04:23:04

回答

0

這應該爲您提供了元素的內容:

$('#infoContainer').html(); 
0

也許你的腳本在DOM前執行加載。

所以,如果你正在操縱DOM元素,你應該等到DOM被加載來操縱它。或者,您可以將腳本標記放置在HTML文檔的末尾。

// These three are equivalent, choose one: 
document.addEventListener('DOMContentLoaded', initializeOrWhatever); 
$(initializeOrWhatever); 
$.ready(initializeOrWhatever); 

function initializeOrWhatever(){ 
    // By the time this is called, the DOM is loaded and you can read/write to it 
    $.getJSON('/foo/', { myData: $('#myInput').val() }, onResponse); 
    function onResponse(res){ 
    $(document).html('<h1>Hello '+res+'</h1>'); 
    }; 
}; 

否則...發佈更多細節和代碼

0

你沒有ID的引用。嘗試設置一個,然後再追加

embedTag.setAttribute("id", "uniqueID"); 
+0

對不起,我沒有在帖子中顯示,但我有一個ID參考。 – user2309644 2013-04-23 05:25:43

+0

我道歉的話..哎 – Silvertiger 2013-04-23 05:28:11

0

看起來您要使用jQuery,但您的示例代碼包含vanilla JavaScript。整個功能可以用下面的jQuery(jsFiddle)被簡化:

(function() { 
    var embedTag = $(document.createElement("embed")); 
    var infoContainer = $("#infoContainer"); 

    if (infoContainer.length) { 
     embedTag.attr({"height": 139, "width": 356}); 
     infoContainer.append(embedTag); 
    } 

    console.log(infoContainer.html()); // This gets you the contents of #infoContainer 
})(); 

jQuery's .get()方法是用於發送GET請求到服務器端腳本。我不認爲它做你想做的事。

+0

克里斯如果我有一個頁面<腳本類型= 「文/ JavaScript的」>上 $(文件)。就緒(函數(){VAR ID爲 「586410650001」; \t \t .. ... ); }); 有沒有辦法從其他頁面獲取ID? – user2309644 2013-04-23 09:06:35

相關問題