简体   繁体   English

为什么jQuery.append不起作用?

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

I am in the middle of creating a small script to 'help' me with my homework. 我正在创建一个小脚本来“帮助”我的作业。 It uses jQuery. 它使用jQuery。 The script (so far) is below: 脚本(到目前为止)如下:

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");

The problem arises when it gets to the 3rd-to-last line. 当到达倒数第三行时,就会出现问题。 Chrome console claims that Object #<HTMLBodyElement> has no method 'append' , however if I extract that line and put it into the console on its own, it works fine. Chrome控制台声称Object #<HTMLBodyElement> has no method 'append' ,但是,如果我提取该行并将其单独放入控制台,则可以正常工作。 I can use a different method to insert HTML, but I would like to know what isn't working with this one. 我可以使用另一种方法来插入HTML,但是我想知道什么不适用于此方法。

Thanks in advance! 提前致谢!

Since you're adding the jQuery script dynamically, it's loaded asynchronously, so it's probably not loaded yet when you're trying to use it. 由于您是动态添加jQuery脚本的,因此它是异步加载的,因此在尝试使用它时可能尚未加载。 Use an onload handler for the dynamic script block: 对动态脚本块使用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");
}

The error message you're getting also indicates that $ exists (another library, maybe?) and is not returning a jQuery object, so you'll probably have to use jQuery in "noConflit" mode, and use jQuery or a user-defined alias instead of $ . 您收到的错误消息还表明$存在(可能是另一个库?),并且没有返回jQuery对象,因此您可能必须在“ noConflit”模式下使用jQuery ,并使用jQuery或用户定义的别名而不是$

Just a guess, but may you are running the script before the browser has finished rendering the DOM? 只是一个猜测,但是您是否可以在浏览器完成DOM渲染之前运行脚本?

Try wrapping the code in 尝试将代码包装在

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

in order to execute it onload. 为了在加载时执行它。

EDIT: changed code to reflect the feedback below, of course one cannot use jQuery's $ before jQuery is loaded, my fault. 编辑:更改代码以反映以下反馈,当然,不能在加载jQuery之前使用jQuery的$

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM