簡體   English   中英

為什么jQuery.append不起作用?

[英]Why isn't jQuery.append working?

我正在創建一個小腳本來“幫助”我的作業。 它使用jQuery。 腳本(到目前為止)如下:

var s = document.createElement('script');
document.body.appendChild(s);
s.src = "http://code.jquery.com/jquery-latest.js"; // Include jQuery

var tmp_1 = document.embeds[0].GetVariable("q1answers"); // Read raw values
var answers_1 = tmp_1.split(","); // Explode into array
answers_1.splice(0,1); // Remove first element (always 0)

var tmp_2 = document.embeds[0].GetVariable("q2answers");
var answers_2 = tmp_2.split(",");
answers_2.splice(0,1);

answers_1.push("LINE_BREAK");
var answers = answers_1.concat(answers_2);

$("body").append("<div id='answers-wrap'></div>");
$("#answers-wrap").css("position", "fixed");
$("#answers-wrap").css("background", "none");

當到達倒數第三行時,就會出現問題。 Chrome控制台聲稱Object #<HTMLBodyElement> has no method 'append' ,但是,如果我提取該行並將其單獨放入控制台,則可以正常工作。 我可以使用另一種方法來插入HTML,但是我想知道什么不適用於此方法。

提前致謝!

由於您是動態添加jQuery腳本的,因此它是異步加載的,因此在嘗試使用它時可能尚未加載。 對動態腳本塊使用onload處理程序:

var s = document.createElement('script');
document.body.appendChild(s);
s.src = "http://code.jquery.com/jquery-latest.js"; // Include jQuery
s.onload = function() {
    $("body").append("<div id='answers-wrap'></div>");
    $("#answers-wrap").css("position", "fixed");
    $("#answers-wrap").css("background", "none");
}

您收到的錯誤消息還表明$存在(可能是另一個庫?),並且沒有返回jQuery對象,因此您可能必須在“ noConflit”模式下使用jQuery ,並使用jQuery或用戶定義的別名而不是$

只是一個猜測,但是您是否可以在瀏覽器完成DOM渲染之前運行腳本?

嘗試將代碼包裝在

window.onload = function(){
   // ... your code here
};

為了在加載時執行它。

編輯:更改代碼以反映以下反饋,當然,不能在加載jQuery之前使用jQuery的$

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM