Using jquery append() in <head> (in a function/class)
I want to use the append()开发者_StackOverflow function from inside the <head>
, in a function to be specific, like so:
function custom_img(src_img)
{
$("div").append("<img src='"+src_img+"'>");
}
var myimg = new custom_img("test.jpg");
This is a quick example that I just wrote out. I want my function to make a new image like that every time I create a new object like this. Obviously this doesn't work, since the append() requires to be in the body (I've tried this).
How would I do this?
The reason it's not working is because your div does not exist yet.
So you can either use the $(document).ready()
function to wait for the document to load.
Or if you want the images to load together with the rest of the document, you could simply create a new div and insert the images there.
var div = $("div")
function custom_img(src) {
div.append($("img").attr("src", src));
}
Then when the document is fully loaded, you can go through the array and insert the loaded images in the DOM.
$(document).ready(function() {
$("#myDiv").append(div);
});
You can try using .after(), or even .html()
function custom_img(src_img)
{
$("div").after("<img src='"+src_img+"'>");
}
var myimg = new custom_img("test.jpg");
or
function custom_img(src_img)
{
$("div").html("<img src='"+src_img+"'>");
}
var myimg = new custom_img("test.jpg");
精彩评论