[英]javascript innerHTML alternative
I am using innerHTML to assign updated value to certain elements on a page. 我正在使用innerHTML将更新的值分配给页面上的某些元素。 However, the innerHTML caused the jquery on the page stopped working, and the css of the page runs out.
但是,innerHTML导致页面上的jquery停止工作,并且页面的css用完了。
So I tried to replace with DOM elements but it's not working. 所以我尝试用DOM元素替换,但是它不起作用。 Any idea how to fix this?
任何想法如何解决这个问题? Thanks !
谢谢 !
var names =['id','name','quantity','description'];
var len = names.length;
for (var i = 0; i < len; i++){
var el = document.getElementById(\'product_\'+names[i]+\'_main\');
var el2 = document.getElementById(\'product_\'+names[i]+selection);
if(el.hasChildNodes()) {
el.replaceChild(el2.firstChild.nodeValue, el.firstChild);
}
if(el && el2) el.innerHTML=el2.innerHTML; /* this part works, but it caused the page CSS to run and jquery no longer working */
}
Since you're using jQuery already, you can use its .html() method: 由于您已经在使用jQuery,因此可以使用其.html()方法:
e1.html( e12.html() );
This should do the same as this: 该操作应与此相同:
el.innerHTML=el2.innerHTML;
If you have JQuery loaded in the page already you can use JQuery selectors and $(element).html() to get the innerHTML. 如果已经在页面中加载了JQuery,则可以使用JQuery选择器和$(element).html()来获取innerHTML。
var names =['id', 'name', 'quantity', 'description'];
for (var i = 0; i < names.length; i++){
var el = $("#product_"+names[i]+"_main");
var el2 = $("#product_"+names[i]+selection);
if (el.children().size() > 0) {
// Your code here
}
if (el && el2) {
el.html() = el2.html();
}
}
Untested code. 未经测试的代码。
el.replaceChild(el2.firstChild.nodeValue, el.firstChild);
Huh, what are you doing there? 呵呵,你在那里做什么? You can't replace a nodeValue, you can only replace nodes:
您不能替换nodeValue,只能替换节点:
el.replaceChild(el2.firstChild, el.firstChild);
this will move the firstChild
of el2
into el
. 这会将
firstChild
的el2
移到el
。 If you want to copy it, you'd need to clone it before. 如果要复制它,则需要先克隆它。 If you want all of the children, you'd need to loop over them.
如果要所有孩子,则需要遍历他们。
If that firstChild
is a text node, you can easily (re)set its value, and copy those of el2: 如果
firstChild
是文本节点,则可以轻松地(重新)设置其值,并复制el2的值:
if (el.firstChild && el.firstChild.nodeType == 3
&& el2.firstChild && el2.firstChild.nodeType == 3)
el.firstChild.nodeValue = el2.firstChild.nodeValue;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.