2013-05-08 91 views
2

我正在使用一些JavaScript來創建新的HTML元素,然後使用MooTools注入方法返回它們。返回HTML元素

display: function() { 
     var threadTitle = new Element('h2',{ 
      'class': 'postItem', 
      'data-id': this.id, 
      'text': this.title, 
      'href': '#', 
      events: { 
       click: function(){ 
        $('newComment').setStyle('visibility', 'visible'); 
        var id = this.get('data-id'); 
        $('thread').value = id; 
        callThread(id); 
       } 
      } 
     }); 

     var deleteT = new Element('a',{ 
      'class': 'deleteItem', 
      'data-id': this.id, 
      'text' : 'Delete', 
      'href' : '#', 

      events: { 
       click: function(){ 
        var deleteID = this.get('data-id'); 
        deleteThread(deleteID) 
       } 
      } 
     }); 

     var editBtn = new Element('input',{ 
      'class': 'mt-btn', 
      'value': 'Edit', 
      'type': 'button', 
      'data-id': this.id, 
      'text' : 'Edit', 
      'href' : '#', 
      events: { 
       click: function(){ 


       } 
      } 
     }); 



     deleteT.inject(threadTitle); 
     editBtn.inject(threadTitle); 
     return threadTitle; 
    } 
}); 

這顯然返回h2內的新元素,因爲我注入它。有沒有一種方法來創建H2的每一個之外,所以從某種意義上講

<h2></h2> 
<a></a> 
<input></input> 

我一直在使用使用editBtn.inject(threadTitle, 'after');的MooTools的方式嘗試,但似乎並沒有工作,沒有東西返回。所以問題是我如何返回一個接一個的頁面上的元素,而不是注入到h2元素中。

+1

等一下,你用的是jQuery嗎? – Ian 2013-05-08 21:17:36

+0

我之所以說這是我發佈的任何問題,要求提供MooTools答案,我似乎得到了一個jQuery答案。感謝這個評論,雖然真的很有幫助。 – joshuahornby10 2013-05-08 21:19:07

+0

我完全是在開玩笑。相信我,我完全理解。如果你標記'mootools'而不是'jquery',你不應該得到一個jQuery答案 – Ian 2013-05-08 21:20:15

回答

1

我嘗試過使用MooTools的方式使用editBtn.inject(threadTitle, 'after');,但這似乎不起作用,沒有任何東西會返回。

它認爲存在的問題是,threadTitle沒有,當你這樣做時,有一個父母。如果它沒有父母,MooTools將很難在「之後」注入任何東西,因爲這樣做需要注入父母元素。

如果你先把threadTitle加入到DOM中,我懷疑editBtn.inject(threadTitle, 'after');這樣可以正常工作。

比較這一點,這不工作:Live Copy

var p = new Element('p'); 
p.set("html", "This is the <code>p</code> element"); 

var div = new Element('div'); 
div.set("html", "This is the <code>div</element> inserted <em>after</em> the <code>p</code>"); 
div.inject(p, 'after'); 

p.inject(document.body); 

...這個,這不:Live Copy

var p = new Element('p'); 
p.set("html", "This is the <code>p</code> element"); 
p.inject(document.body); 

var div = new Element('div'); 
div.set("html", "This is the <code>div</element> inserted <em>after</em> the <code>p</code>"); 
div.inject(p, 'after'); 

...的區別在於p因素是在我們嘗試在其後注入div之前添加到DOM。

+0

啊,我明白了。完美的一個問題,而不是注入到document.body可以注入到一個div?這將是p.inject($(divName)); – joshuahornby10 2013-05-08 21:33:23

+0

@ joshuahornby10:只要元素有一個父元素,它應該與父元素無關。例如,看看這個:http:// jsfiddle。net/p2M3h/2 /父母在我的一個孩子後注入的時候,甚至沒有在DOM中。這個問題(我認爲)是'bar.inject(foo,'after')'基本上是作爲原始DOM操作'foo.parentNode.insertBefore(bar,foo)'實現的,所以如果'foo'沒有父類,它不能工作。 – 2013-05-08 21:36:02

+0

有人說MooTools! – samosaris 2015-12-10 14:21:39