如何根据按下按钮显示div下的表单

时间:2018-01-12 15:12:50

标签: javascript jquery html

我需要使用JavaScript在div下显示一个表单,具体取决于我传递给创建表单的函数的外部id。

function reply(reply){
    var form = document.createElement('form');
    var textfield = document.createElement('textfield')
    var submit = document.createElement('input')
    form.setAttribute('action',"\"sendcomment("+ array[i].pk +")\"" )
    textfield.className = "commenttextfield"
    textfield.setAttribute('placeholder',"reply..." )
    submit.setAttribute('type',"submit" )
    submit.className="commentformsubmit"
    form.appendChild(textfield);
    form.appendChild(submit);
}

我有很多div,其中id为comment-id-X,其中X是唯一的数字.X的值作为回复传递给上面的函数。所以我需要做一些像form.placeunder("comment-box-"+ reply)这样的事情。我试着这样做:

document.getElementById('comment-id-'+ reply).appendChild(form);

会导致错误说明:

TypeError: document.getElementById(...) is null.

是什么导致了这个?

此外,div还有一个可变的左边距样式属性,我希望表单也有。这可能吗?

我需要附加的div是由javascript生成的,如下所示:

for(var i = 0; i < array.length; i++) {
    //setup list item
    var item = document.createElement('li');
    item.clasName = "commentlistelement"
    //setup parent div
    var maindiv = document.createElement('div')
    maindiv.setAttribute('id',"comment-id-" + array[i].pk);
    maindiv.className = "row comment";
    maindiv.setAttribute("style","padding-left: "+3*array[i].fields.indent+"vw;");
    //fill parent div (the reply button triggers the function above)
    maindiv.innerHTML = "<div class=\"col-md-1\">profile<br>pic</div><div class=\"col-md-9\"><small>username  </small><small><button class=\"buttonlink\" onclick=\"reply("+ array[i].pk +")\">reply</button></small><br><p>" + array[i].fields.description + "</p></div>"
    //append div to list item and list item to list
    item.appendChild(maindiv);
    list.appendChild(item);
}

1 个答案:

答案 0 :(得分:1)

这是我解决问题的方法,但在此之前我想提一些事情 1 - html中没有textfield元素(也许你错了这个用于textarea)
2 - 你必须重命名你的变量回复功能回复,这样你的代码就会混淆他们

function replyFn() {
  var form = document.createElement('form');
  form.className = 'formcomment'
  var textarea = document.createElement('textarea')
  var submit = document.createElement('input')
  //form.setAttribute('action', "\"sendcomment(" + array[i].pk + ")\"")
  textarea.className = "commenttextfield"
  textarea.innerText = "reply..."
  submit.setAttribute('type', "submit")
  submit.className = "commentformsubmit"
  form.appendChild(textarea);
  form.appendChild(submit);
  return form;
}

function showForm(reply) {

  var form = replyFn();
  document.getElementById('comment-id-' + reply).appendChild(replyFn());
  alert(document.getElementsByClassName('formcomment').length)

}
<input type="button" value="reply" onclick="showForm(1)">
<div id="comment-id-1" class="comment-id-1"></div>