开发者

Using jquery append() in <head> (in a function/class)

开发者 https://www.devze.com 2022-12-28 19:42 出处:网络
I want to use the append()开发者_StackOverflow function from inside the <head>, in a function to be specific, like so:

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

精彩评论

暂无评论...
验证码 换一张
取 消