2013-03-23 51 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); 
} 
相关问题