innerHTML的替代方案? [英] Alternative for innerHTML?

查看:1580
本文介绍了innerHTML的替代方案?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有办法在不使用innerHTML的情况下更改HTML中任何内容的文本。

I'm wondering if there's a way to change the text of anything in HTML without using innerHTML.

我问的原因是因为它有点不满意W3C。
我知道这是挑剔,但我只是想知道,有办法吗?

Reason I'm asking is because it's kinda frowned upon by the W3C. I know it's nitpicking, but I just wanna know, is there a way?

编辑:人们似乎误解了我在这里问的问题:我想要找到一种方法来有效地改变正在显示的文字。

people seem to misunderstand what I'm asking here: I want to find a way to effectivly change the text being displayed.

如果我有:

<div id="one">One</a>

innerHTML允许我这样做:

innerHTML allows me to do this:

var text = document.getElementsById("one");
text.innerHTML = "Two";

我的屏幕上的文字会有所改变。

我不知道希望附加更多文本,我希望更改现有文本。

And the text on my screen will have changed.
I do not wish to append more text, I wish to change allready existing text.

推荐答案

推荐的方法是通过DOM操作,但它可以相当冗长。例如:

The recommended way is through DOM manipulation, but it can be quite verbose. For example:

// <p>Hello, <b>World</b>!</p>
var para = document.createElement('p');
para.appendChild(document.createTextNode('Hello, '));

// <b>
var b = document.createElement('b');
b.appendChild(document.createTextNode('World');
para.appendChild(b);

para.appendChild(document.createTextNode('!'));

// Do something with the para element, add it to the document, etc.

编辑

为了响应您的编辑,为了替换当前内容,您只需删除现有内容,然后使用以上代码填写新内容。例如:

In response to your edit, in order to replace the current content, you simply remove the existing content, then use the code above to fill in new content. For example:

var someDiv = document.getElementById('someID');
var children = someDiv.childNodes;
for(var i = 0; i < children.length; i++)
    someDiv.removeChild(children[i]);

但正如其他人所说,我建议使用类似jQuery的东西,因为并非所有浏览器都完全支持DOM,而且有JavaScript的库在内部处理。例如,jQuery看起来像这样:

But as someone else said, I'd recommend using something like jQuery instead, as not all browsers fully support DOM, and those that do have quirks which are dealt with internally by JavaScript libraries. For example, jQuery looks something like this:

$('#someID').html("<p>Hello, <b>World</b>!</p>");

这篇关于innerHTML的替代方案?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆