【推荐】2019 Java 开发者跳槽指南.pdf(吐血整理) >>>
我有一个表示元素的HTML字符串: '<li>text</li>'
。 我想将其附加到DOM中的元素(以我的情况为ul
)。 如何使用Prototype或DOM方法做到这一点?
(我知道我可以在jQuery中轻松完成此操作,但不幸的是,我们没有使用jQuery。)
#1楼
这也将起作用:
$('<li>').text('hello').appendTo('#mylist');
感觉更像是带有链接函数调用的jquery方式。
#2楼
var jtag = $j.li({ child:'text' }); // Represents: <li>text</li>
var htmlContent = $('mylist').html();
$('mylist').html(htmlContent + jtag.html());
使用jnerator
#3楼
迟了,但只是作为笔记;
可以向目标元素添加一个琐碎的元素作为容器,并在使用后将其删除。
//在chrome 23.0,firefox 18.0(即7-8-9和Opera 12.11)上进行了测试。
<div id="div"></div>
<script>
window.onload = function() {
var foo, targetElement = document.getElementById('div')
foo = document.createElement('foo')
foo.innerHTML = '<a href="#" target="_self">Text of A 1.</a> '+
'<a href="#" onclick="return !!alert(this.innerHTML)">Text of <b>A 2</b>.</a> '+
'<hr size="1" />'
// 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)
}
</script>
#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="<img src='//placekitten.com/100/100'>foo<i>bar</i>".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')"
}));
来源:oschina
链接:https://my.oschina.net/u/3797416/blog/3155778