如何设置属性到创建的元素? [英] How to set attribute to created element ?
本文介绍了如何设置属性到创建的元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想直接将标签发布到html体内,但是一个新问题是我发现未定义值的错误按摩,检查我的代码建议我该怎么办?
我尝试了什么:
i want to directly post tags into html body but a new problem is that i found error massages of undefined values, check my code suggest me what to do ?
What I have tried:
function body(el,at,txt)
{
el = document.createElement(el);
p.setAttribute(at);
t = document.createTextNode(txt);
el.appendChild(t);
}
body("p", "id='demo'", "i m paragraph");
/* this code doesnt work why */
推荐答案
试试这个
try this
<script>
function body(el, at, txt) {
var elem = document.createElement(el);
var keyvalue = at.split('='); // split to get key and value
elem.setAttribute(keyvalue[0], keyvalue[1]); // setAttribute accepts 2 param (key and value )
t = document.createTextNode(txt);
elem.appendChild(t);
document.body.appendChild(elem); // append the element to body
}
body("p", "id=demo", "i m paragraph"); // remove the single quotes
</script>
这篇关于如何设置属性到创建的元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文