在js中创建属性会触发异常'而不是函数'

Maj*_* DH 2 html javascript firefox scratchpad

我正在使用js来改变内容输入的div的内容我希望用它们与Ajax一起使用,我使用Firefox暂存器来调试这个函数:

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);
}
Run Code Online (Sandbox Code Playgroud)

我得到的是这个:

/*
Exception: document.createElement(...).createAttribute is not a function
@Scratchpad/2:2
*/
Run Code Online (Sandbox Code Playgroud)

我什么都不懂,有什么想法?

nnn*_*nnn 5

我认为.createAttribute()属于document,而不是单个元素,因此可以解释该错误:.createElement()返回一个元素,并且该元素没有任何功能.createAttribute().

但是.createAttribute()在调用之前不需要使用.setAttribute(),因为后者将创建元素属性(如果它们尚不存在).但是,我认为.setAttribute()回报undefined所以你不能真正链接它.尝试一次一步:

var input1 = document.createElement('input');
input1.setAttribute('type', 'hidden');
input1.setAttribute('value',id );
input1.setAttribute('name','id' );
// etc.
Run Code Online (Sandbox Code Playgroud)