简体   繁体   中英

How to inject an image inside a div using its class as selector

I cant get this to work, I want to create a new element DIV with id = item and class = item+variable, like this:

<div id="item" class="item1"></div>

and then inject an image inside by selecting the newly created divs class resulting with something like this:

<div id="item" class="item1">
   <img src="images/1.png" style="width: 64px; height: 64px;">
</div>

I think my problem is with my last inject selector, but im not sure, the div creates itself but doesnt inject the image.

var content = this.options.content;
var id = this.options.id;

new Element('div', {id: 'item', class: 'item'+id}).inject($('slot'+id));        
new Element('img',{ src:'images/'+content+'.png', style:'width: 64px; height: 64px;' }).inject($('.item'+id));

you can use

var g = new Element('div', {id: 'item', class: 'item'+id}).inject($('slot'+id));        
new Element('img',{  style:'width: 64px; height: 64px;' }).inject(g);

I am not a mootools expert by any stretch of the imagination, but I think the inject method requires a single element as a parameter and $('.item'+id) does not get you a single element (in fact it returns null), both because you're giving it a class argument instead of an ID and because the item you're searching for is not yet in the DOM.

Instead, you can just keep track of the element that you just previously crated.

Here's a piece of sample code that works:

var id = 1;

var el = new Element('div', {id: 'item', class: 'item'+id}).inject($('slot'+id));        
new Element('img',{ src:'http://photos.smugmug.com/photos/344291068_HdnTo-Ti.jpg', style:'width: 100px; height: 66px;' }).inject(el);

And, a jsFiddle: http://jsfiddle.net/jfriend00/czNTL/

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