简体   繁体   中英

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. 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. I can use a different method to insert HTML, but I would like to know what isn't working with this one.

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. Use an onload handler for the dynamic script block:

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 $ .

Just a guess, but may you are running the script before the browser has finished rendering the 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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