如何在JavaScript中替换一些字符串变量的文本?

编程入门 行业动态 更新时间:2024-10-12 22:26:24
本文介绍了如何在JavaScript中替换一些字符串变量的文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我知道这是一个非常简单的问题,但是我需要在每次平均触发时用一个变量替换一段段落中的文本。

I know this is a really simple question, but I need to replace this bit of text in a paragraph with a variable every time an even fires.

标记看起来像这样

"www.w3/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="www.w3/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Untitled Document</title> <style> #container {width:100%; text-align:center; } #heading {width:100%; text-align:center; } </style> </head> <div id="heading"> <h1>hello</h1> </div> <body> <div id="container"> <textarea name="mytextarea" cols="60" rows="40"></textarea> </div> </body> </html>

我需要的是在标签中显示hello的地方,就是将它变成一个变量那辆面包车将被我将生成的一个字符串所替代。

What I need is where it says "hello" in the tags, is for that to be a variable that van be replaced by a string that I will generate.

推荐答案

一个例子,简单的事情如何变得复杂:)

One example on how can be simple things made complicated :)

javascript:

javascript:

// simple way: function replace_text(text) { var heading = document.getElementById('heading'); heading.innerHTML = '<h1>' + text + '</h1>'; } // complicated way: function replace_text2(text) { var heading = document.getElementById('heading'); var node = heading.childNodes[0]; while ( node && node.nodeType!=1 && node.tagName!='H1' ){ //console.log(node.nodeType,node); node = node.nextSibling; } if (node) { node.replaceChild(document.createTextNode(text),node.childNodes[0]); } }

html:

<input type="button" onclick="replace_text('HELLO 1!');" value="Replace 1st text" /> <input type="button" onclick="replace_text2('HELLO 2!');" value="Replace 2nd text" />

脚本在这里。

更多推荐

如何在JavaScript中替换一些字符串变量的文本?

本文发布于:2023-11-30 07:07:25,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1649118.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   变量   文本   如何在   JavaScript

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!