簡體   English   中英

Javascript追加子巢

[英]Javascript append child nest

我正在嘗試創建其中的幾個:

 <div class="form-group">
        <label class="col-sm-2 control-label" for="observation">Observation</label>
        <div class="col-sm-10">
          <textarea class="form-control" id="paragraphx" name="whatever" placeholder="test">
    test</textarea>
        </div>
 </div>

使用以下JavaScript:

function addParagraph()
{
     var div1=document.createElement('div');
     var div2=document.createElement('div');
     var label=document.createElement('label');
     var text=document.createElement('textarea');

     div1.setAttribute('class','form-group');
     div2.setAttribute('class','col-sm-10');

     label.setAttribute('class','col-sm-2 control-label');
     label.setAttribute('for','paragraph');
     label.setAttribute('id','paragraph'+p);

     text.setAttribute('class','form-control');
     text.setAttribute('id','paragraph');
     text.setAttribute('name','item'+i);
     text.setAttribute('placeholder','Add another paragraph here.');

     div2.appendChild(text);
     label.appendChild(div2);
     div1.appendChild(label);

     document.getElementById('myForm').appendChild(div1);
     document.getElementById("paragraph"+p).innerHTML = "Paragraph";
     increment();
}

但是,這是唯一以HTML呈現的內容

<div class="form-group">
   <label id="paragraph1" for="xxxxxx" class="col-sm-2 control-label">Paragraph
   </label>
</div>

我究竟做錯了什么? 標簽不應該添加div2作為其子級嗎? 還是我以錯誤的方式使用AppendChild?

*****編輯*****

伙計們,非常感謝您的投入。 我現在唯一的問題是嘗試使占位符在加載文本框后實際加載。 例如,現在僅在我單擊文本框后才顯示占位符。

問題是這條線

   document.getElementById("paragraph"+p).innerHTML = "Paragraph";

您正在破壞label元素的html內容。 嘗試對此發表評論,您將看到您得到的!

另外,我注意到這些線

 div2.appendChild(text);
 label.appendChild(div2);
 div1.appendChild(label);

將產生此輸出

<div class="form-group">
   <label id="paragraph1" for="xxxxxx" class="col-sm-2 control-label">
      <div><textarea></textarea></div>
   </label>
</div>

我想你想做的是

 div2.appendChild(text);
 div1.appendChild(div2);
 div1.appendChild(label);

那將產生您的預期輸出。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM