2013-03-23 29 views
2

我正在使用js來更改div的內容,該內容輸入我想用它們與Ajax, 我已經使用Firefox便箋簿調試此功能:在js中創建屬性觸發異常'不是函數'

function show(id){ 
var div = document.getElementById('com'); 
div.innerHTML = ''; 
var input1 = document.createElement('input') 
      .createAttribute('type').setAttribute('type', 'hidden') 
      .createAttribute('value').setAttribute('value',id) 
      .setAttribute('name','id'); 
var input2 = document.createElement('input') 
      .createAttribute('type').setAttribute('type', 'input') 
      .createAttribute('name').setAttribute('name', 'com'); 
var btn = document.createElement('button') 
      .createAttribute('onClick').setAttribute('onClick', 'post()'); 
btn.innerHTML = 'Comment'; 
div.appendChild(input1).appendChild(input2).appendChild(btn); 
} 

和我得到的是這樣的:

/* 
Exception: document.createElement(...).createAttribute is not a function 
@Scratchpad/2:2 
*/ 

我明白了什麼,什麼想法?

回答

3

我相信.createAttribute()屬於document,而不是單獨的元素,所以這將解釋錯誤:.createElement()返回元素,而這個元素沒有功能.createAttribute()

但是在調用.setAttribute()之前,您不需要使用.createAttribute(),因爲如果它們不存在,後者將創建元素屬性。不過,我認爲.setAttribute()返回undefined,所以你不能真正鏈接它。嘗試一次只做一步:

var input1 = document.createElement('input'); 
input1.setAttribute('type', 'hidden'); 
input1.setAttribute('value',id); 
input1.setAttribute('name','id'); 
// etc. 
3

基本上,例外說沒有稱爲「createAttribute」的函數。這是正確的:

.createAttribute()document功能:https://developer.mozilla.org/en-US/docs/DOM/document#Methods

所以功能不能捆綁,像你盡力去做。你必須分別打電話給他們。無論如何,不​​應該再使用「createAttribute」(請參閱​​Using createAttribute vs. just setting the attribute directly?)。

function show(id){ 
    var div = document.getElementById('com'); 
    div.innerHTML = ''; 

    var input1 = document.createElement('input'); 
    input1.setAttribute('type', 'hidden'); 
    input1.setAttribute('value',id); 
    input1.setAttribute('name','id'); 

    var input2 = document.createElement('input'); 
    input2.setAttribute('type', 'input'); 
    input2.setAttribute('name', 'com'); 

    var btn = document.createElement('button'); 
    btn.setAttribute('onClick', 'post()'); 
    btn.innerHTML = 'Comment'; 

    div.appendChild(input1).appendChild(input2).appendChild(btn); 
}