简体   繁体   English

如何替换 div 元素内的文本?

[英]How do I replace text inside a div element?

I need to set the text within a DIV element dynamically.我需要在 DIV 元素中动态设置文本。 What is the best, browser safe approach?最好的浏览器安全方法是什么? I have prototypejs and scriptaculous available.我有prototypejs和scriptaculous可用。

<div id="panel">
  <div id="field_name">TEXT GOES HERE</div>
</div>

Here's what the function will look like:下面是函数的样子:

function showPanel(fieldName) {
  var fieldNameElement = document.getElementById('field_name');
  //Make replacement here
}

您可以简单地使用:

fieldNameElement.innerHTML = "My new text!";

Updated for everyone reading this in 2013 and later:为 2013 年及以后阅读本文的所有人更新:

This answer has a lot of SEO, but all the answers are severely out of date and depend on libraries to do things that all current browsers do out of the box.这个答案有很多搜索引擎优化,但所有答案都严重过时,并且依赖库来做所有当前浏览器开箱即用的事情。

To replace text inside a div element, use Node.textContent, which is provided in all current browsers. 要替换 div 元素内的文本,请使用 Node.textContent,它在所有当前浏览器中都提供。

fieldNameElement.textContent = "New text";

function showPanel(fieldName) {
  var fieldNameElement = document.getElementById("field_name");
  while(fieldNameElement.childNodes.length >= 1) {
    fieldNameElement.removeChild(fieldNameElement.firstChild);
  }
  fieldNameElement.appendChild(fieldNameElement.ownerDocument.createTextNode(fieldName));
}

The advantages of doing it this way:这样做的好处是:

  1. It only uses the DOM, so the technique is portable to other languages, and doesn't rely on the non-standard innerHTML它只使用 DOM,因此该技术可移植到其他语言,并且不依赖于非标准的 innerHTML
  2. fieldName might contain HTML, which could be an attempted XSS attack. fieldName 可能包含 HTML,这可能是尝试的 XSS 攻击。 If we know it's just text, we should be creating a text node, instead of having the browser parse it for HTML如果我们知道它只是文本,我们应该创建一个文本节点,而不是让浏览器将其解析为 HTML

If I were going to use a javascript library, I'd use jQuery, and do this:如果我要使用 javascript 库,我会使用 jQuery,然后执行以下操作:


  $("div#field_name").text(fieldName);

Note that @AnthonyWJones' comment is correct: "field_name" isn't a particularly descriptive id or variable name.请注意, @AnthonyWJones 的评论是正确的:“field_name”不是一个特别具有描述性的 id 或变量名称。

I would use Prototype's update method which supports plain text, an HTML snippet or any JavaScript object that defines a toString method.我会使用 Prototype 的update方法,它支持纯文本、HTML 片段或任何定义toString方法的 JavaScript 对象。

$("field_name").update("New text");
$('field_name').innerHTML = 'Your text.';

One of the nifty features of Prototype is that $('field_name') does the same thing as document.getElementById('field_name') . Prototype 的一项漂亮功能是$('field_name')document.getElementById('field_name')做同样的事情。 Use it!用它! :-) :-)

John Topley's answer using Prototype's update function is another good solution. John Topley 使用 Prototype 的update功能的回答是另一个很好的解决方案。

The quick answer is to use innerHTML (or prototype's update method which pretty much the same thing).快速答案是使用innerHTML(或原型的更新方法,它们几乎相同)。 The problem with innerHTML is you need to escape the content being assigned. innerHTML 的问题是您需要转义被分配的内容。 Depending on your targets you will need to do that with other code OR根据您的目标,您需要使用其他代码或

in IE:-在 IE 中:-

document.getElementById("field_name").innerText = newText;

in FF:-在FF:-

document.getElementById("field_name").textContent = newText;

(Actually of FF have the following present in by code) (实际上FF的代码中存在以下内容)

HTMLElement.prototype.__defineGetter__("innerText", function () { return this.textContent; })

HTMLElement.prototype.__defineSetter__("innerText", function (inputText) { this.textContent = inputText; })

Now I can just use innerText if you need widest possible browser support then this is not a complete solution but neither is using innerHTML in the raw.现在,如果您需要尽可能广泛的浏览器支持,我可以只使用innerText,那么这不是一个完整的解决方案,但也不是在原始版本中使用innerHTML。

If you really want us to just continue where you left off, you could do:如果您真的希望我们从您离开的地方继续,您可以这样做:

if (fieldNameElement)
    fieldNameElement.innerHTML = 'some HTML';

nodeValue is also a standard DOM property you can use: nodeValue 也是您可以使用的标准 DOM 属性:

function showPanel(fieldName) {
  var fieldNameElement = document.getElementById(field_name);
  if(fieldNameElement.firstChild)
    fieldNameElement.firstChild.nodeValue = "New Text";
}
el.innerHTML='';
el.appendChild(document.createTextNode("yo"));

If you're inclined to start using a lot of JavaScript on your site, jQuery makes playing with the DOM extremely simple.如果您倾向于开始在您的站点上使用大量 JavaScript,jQuery 可以让使用 DOM 变得非常简单。

http://docs.jquery.com/Manipulation http://docs.jquery.com/Manipulation

Makes it as simple as: $("#field-name").text("Some new text.");让它变得如此简单: $("#field-name").text("Some new text.");

如果您不能假设结构,请使用 innerText - 使用 Text#data 更新现有文本性能测试

function showPanel(fieldName) {
  var fieldNameElement = document.getElementById(field_name);

  fieldNameElement.removeChild(fieldNameElement.firstChild);
  var newText = document.createTextNode("New Text");
  fieldNameElement.appendChild(newText);
}

Here's an easy jQuery way:这是一个简单的jQuery方法:

var el = $('#yourid .yourclass');

el.html(el.html().replace(/Old Text/ig, "New Text"));

In HTML put this在 HTML 中把这个

<div id="field_name">TEXT GOES HERE</div>

In Javascript put this在 Javascript 中把这个

var fieldNameElement = document.getElementById('field_name');
        if (fieldNameElement)
        {fieldNameElement.innerHTML = 'some HTML';}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM