2016-01-01 76 views
-1

我想改變我的輸入框與warnnig類和glyphicons,所以通過Dom單擊確定後,我想更改類並添加新的span標記。DOM代碼有什麼問題?

 <body> 
<div class="container"> 
<div class="row"> 
    <div class="col-md-10 "> 
     <form class=""> 
      <div class="form-group" id="namediv"> 
       <label for="name">Name</label> 
       <input type="text" class="form-control" name="name" id="name"> 
      </div> 

      <input type="button" class="btn btn-primary btn-lg" id="n_button" name="n_button" value="ok"> 
      </form> 
    </div> 
</div> 
</div> 
<script> 
    var a = document.getElementById('n_button'); 
    a.addEventListener('click',function(){ 
    var ediv = document.getElementById('namediv'); 
      ediv.className = ediv.className +' form-group has-warning has-feedback'; 
      //ediv.classList.add("has-warning") 

      var name = document.getElementById('name'); 
      var span1 = document.createElement('span'); 
      span1.className = "glyphicon glyphicon-warning-sign form-control-feedback" ; 
      span1.setAttribute("aria-hidden",'true'); 
      name.appendChild(span1) ; 
      var span2 = document.createElement('span'); 
      span2.className = "sr-only" ; 
      span2.setAttribute("id",'inputWarning2Status'); 
      span1.appendChild(span2); 
     },false) ; 
     </script> 

回答

0

您不能插入DOMElementinput,則需要使用父元素,在這種情況下,DOMElement與ID namediv

var a = document.getElementById('n_button'); 
 

 
a.addEventListener('click', function() { 
 
    var ediv = document.getElementById('namediv'); 
 
    ediv.className = ediv.className + ' form-group has-warning has-feedback'; 
 

 
    var span1 = document.createElement('span'); 
 
    span1.className = "glyphicon glyphicon-warning-sign form-control-feedback"; 
 
    span1.setAttribute("aria-hidden", 'true'); 
 
    ediv.appendChild(span1); 
 

 
    var span2 = document.createElement('span'); 
 
    span2.className = "sr-only"; 
 
    span2.setAttribute("id", 'inputWarning2Status'); 
 
    span1.appendChild(span2); 
 
}, false);
/* only for example */ 
 
.form-control-feedback { 
 
    width: 100px; 
 
    height: 100px; 
 
    border: 1px solid red; 
 
    display: inline-block; 
 
}
<div class="container"> 
 
    <div class="row"> 
 
    <div class="col-md-10 "> 
 
     <form class=""> 
 
     <div class="form-group" id="namediv"> 
 
      <label for="name">Name</label> 
 
      <input type="text" class="form-control" name="name" id="name"> 
 
     </div> 
 

 
     <input type="button" class="btn btn-primary btn-lg" id="n_button" name="n_button" value="ok"> 
 
     </form> 
 
    </div> 
 
    </div> 
 
</div>