如果您将 DOM 中的元素作为对象而不是原始字符串表示形式移动,则它们附加的事件和其他元数据将被保留。
您需要使用 DOM 的 appendChild 和 insertBefore 方法。小提琴:http://jsfiddle.net/QMLpL/2/
这是您更新后的 sn-p:
prepend: function(newNode) {
this.node.insertBefore(newNode,this.node.firstChild);
},
append: function(newNode) {
this.node.appendChild(newNode);
}
更新后的 sn-p 需要一个 DOM 节点而不是字符串。
如果您需要一个字符串,请考虑将该字符串用作 CDATA 节点:
node = document.createTextNode(str);
增强的小提琴:http://jsfiddle.net/QMLpL/3/
用法:
prepend: function(str) {
newNode = document.createTextNode(str);
this.node.insertBefore(newNode,this.node.firstChild);
},
append: function(str) {
newNode = document.createTextNode(str);
this.node.appendChild(newNode);
}
链接小提琴的内容如下。
HTML:
<div id="one">
<p><a id="clicky" href="#">Hello World</a></p>
</div>
<div id="two">
<p>Lorem Ipsum</p>
</div>
JavaScript:
var clicky = document.getElementById('clicky');
clicky.onclick = function() {
console.log('clicked!');
return false;
};
function append(target,node) {
if ( typeof node === 'string' ) {
node = document.createTextNode(node); // cast string as CDATA
}
target.appendChild(node);
}
function prepend(target,node) {
if ( typeof node === 'string' ) {
node = document.createTextNode(node);
}
target.insertBefore(node,target.firstChild);
}
var twoDiv = document.getElementById('two');
append(twoDiv,clicky);
var newElement = document.createElement('p');
newElement.onclick = function() {
console.log('clicked the p');
return false;
};
newElement.appendChild(document.createTextNode('Dolor sit amet.')); // add a CDATA node to the new P element
prepend(twoDiv,newElement);
append(twoDiv,'Waddup?');