为什么jQuery.append不工作?

mic*_*bug 0 javascript jquery

我正在创建一个小脚本来"帮助"我完成我的作业.它使用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");
Run Code Online (Sandbox Code Playgroud)

当它到达倒数第3行时会出现问题.Chrome控制台声称Object #<HTMLBodyElement> has no method 'append',如果我提取该行并将其单独放入控制台,它可以正常工作.我可以使用不同的方法来插入HTML,但我想知道什么不适用于这个.

提前致谢!

bfa*_*tto 7

由于您是动态添加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");
}
Run Code Online (Sandbox Code Playgroud)

你得到的错误信息也表明$存在(另一个库,可能?)并且没有返回jQuery对象,所以你可能不得不在"noConflit"模式下使用jQuery,而是使用jQuery或者用户定义的别名代替的$.