javascript - js中创建属性触发异常 'not a function'

标签 javascript html 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);
}

我得到的是:

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

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

最佳答案

我相信 .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.

关于javascript - js中创建属性触发异常 'not a function',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15585908/

相关文章:

Javascript : Ajax and Show/Hide Div

javascript - 如何让图片与按钮互动?

html - 输入类型 ="button"元素是只读的吗? Firefox 似乎是这么认为的 :

javascript - 我可以使用 Python 和 Selenium 的正则表达式找到一个元素吗?

javascript - HTML5 - 将 Web SQL 数据库导出到 csv 或 txt 文件

javascript - 使用 django-el-pagination(惰性分页)保留浏览器历史记录

javascript - HTML5 EventSource 数据函数处理先前值,而不是当前值

javascript - 如何向文本框数组添加值

用于查看请求的 Firefox 插件

javascript - Firefox 17.0.1 扩展无法访问文件