2011-10-28 120 views
1

對不起,如果已經被覆蓋了,我已經看了一下,但沒有提出一個問題 - 答案(我在過去發現了很多關於我的問題的答案 - 保持良好工作傢伙+女孩)Mootools元素注入

我學習Mootools元素注射,我沒有使用這個很長的時間,我發現它是開放我的眼睛各種用法。我的問題是我如何構建一個鏈接到一個URL的新圖像元素?例如我如何注入;

<a href="[url]"><img src="[path]" /></a> 

我能做到這一點的2個獨立的元素&而是奮力將它們合併爲一個單元。感謝您閱讀我的問題和任何建議。

馬克

+0

感謝您的答覆,我一直嘗試並紛紛拿出以下解決方案適合我的需要 (el)是一個新的元素('img',{ 'src':photo.src })。 , defaultLink = new Element('a','class':'makeImageDefault','name':phot '後' o.id })注入(圖像), defaultImageIcon =新元素( 'IMG',{ 'SRC':。photo.defaultIcon })注入(defaultLink, '內部') EL。注($( 'photoGrid')); }); – Gravesy

+0

一旦注射完成,現在即時面臨第二個問題。注入class =「makeImageDefault」的鏈接連接到$$('a.makeImageDefault')。注入後啓動新注入的addEvent()不起作用 – Gravesy

回答

2

使用Elements.from,它快速,完全有效且簡單。

var collection = '<a href="{href}"><img src="{src}" /></a>'; 
Elements.from(collection.substitute({ 
    href: 'http://www.stackoverflow.com', 
    src: 'http://www.placekitten.com/300/300' 
})).inject(document.body); 

一個明顯的缺點是您沒有對創建的節點的引用,只對元素的集合進行引用。

+0

+1,特別是'.substitute',它是如此沒用! Elements.from是對mootools-more http://mootools.net/docs/more/Element/Elements.From的依賴。 –

+0

+1,比我的答案好得多。我還在學習MooTools,所以這是有幫助的':)' –

+0

@DimitarChristoff,我喜歡'.subsitutute',我希望我們可以使用它的路徑,即。 '''.substitute({link:{url:'/'}})' –

1

你可以使用兩個新元素(一個imgagrabinject窩他們:

var anchor = new Element("a", { 
    href: "http://www.stackoverflow.com" 
}); 

var img = new Element("img", { 
    src: "http://www.placekitten.com/300/300" 
}); 

// inject the img into the anchor 
img.inject(anchor); 

// Append the anchor into the body: 
document.body.grab(anchor); 

,這將產生以下HTML:

<a href="http://www.stackoverflow.com"> 
    <img src="http://www.placekitten.com/300/300"> 
</a> 

例如:http://jsfiddle.net/tNamz/

0

感謝您的答覆,我一直嘗試,並已拿出以下解決方案適合我的需要

photos.each(function(photo){ 
    var el = new Element('div.image'), 
    image = new Element('img', { 
     'src': photo.src 
    }).inject(el), 
    defaultLink = new Element('a', { 
     'class': 'makeImageDefault', 'name': photo.id 
    }).inject(image, 'after'), 
    defaultImageIcon = new Element('img', { 
     'src': photo.defaultIcon 
    }).inject(defaultLink, 'inside') 
    el.inject($('photoGrid')); 
}); 
+0

一旦注射完成,現在即時面臨第二個問題。注入class =「makeImageDefault」的鏈接連接到$$('a.makeImageDefault')。注入後啓動新注入的addEvent()不起作用 – Gravesy

+0

祝賀解決方案。如果可以,請確保將您的答案標記爲「已接受」,以便其他人可以向您學習成功。乾杯〜 –