我有一个表示元素的HTML字符串: '
text' 。 我想将其附加到DOM中的元素(以我的情况为ul )。 如何使用Prototype或DOM方法做到这一点?(我知道我可以在jQuery中轻松完成此操作,但不幸的是,我们没有使用jQuery。)
#1楼
这也将起作用:
$('
').text('hello').appendTo('#mylist');感觉更像是带有链接函数调用的jquery方式。
#2楼
var jtag = $j.li({ child:'text' }); // Represents:
textvar htmlContent = $('mylist').html();
$('mylist').html(htmlContent + jtag.html());
#3楼
迟了,但只是作为笔记;
可以向目标元素添加一个琐碎的元素作为容器,并在使用后将其删除。
//在chrome 23.0,firefox 18.0(即7-8-9和Opera 12.11)上进行了测试。
window.onload = function() {
var foo, targetElement = document.getElementById('div')
foo = document.createElement('foo')
foo.innerHTML = 'Text of A 1. '+
'Text of A 2. '+
'
'
// Append 'foo' element to target element
targetElement.appendChild(foo)
// Add event
foo.firstChild.onclick = function() { return !!alert(this.target) }
while (foo.firstChild) {
// Also removes child nodes from 'foo'
targetElement.insertBefore(foo.firstChild, foo)
}
// Remove 'foo' element from target element
targetElement.removeChild(foo)
}
#4楼
这是一种简单的方法:
String.prototype.toDOM=function(){
var d=document
,i
,a=d.createElement("div")
,b=d.createDocumentFragment();
a.innerHTML=this;
while(i=a.firstChild)b.appendChild(i);
return b;
};
var foo="foobar".toDOM();
document.body.appendChild(foo);
#5楼
对于这个问题,我想我会想出一些复杂但又简单的方法,也许有人会发现有用的东西。
/*Creates a new element - By Jamin Szczesny*/
function _new(args){
ele = document.createElement(args.node);
delete args.node;
for(x in args){
if(typeof ele[x]==='string'){
ele[x] = args[x];
}else{
ele.setAttribute(x, args[x]);
}
}
return ele;
}
/*You would 'simply' use it like this*/
$('body')[0].appendChild(_new({
node:'div',
id:'my-div',
style:'position:absolute; left:100px; top:100px;'+
'width:100px; height:100px; border:2px solid red;'+
'cursor:pointer; background-color:HoneyDew',
innerHTML:'My newly created div element!',
value:'for example only',
onclick:"alert('yay')"
}));