Joh*_*hn 111 html javascript
我在我的HTML中有1个按钮和一些文本,如下所示:
function get_content(){
// I don't know how to do in here!!!
}
<input type="button" onclick="get_content()" value="Get Content"/>
<p id='txt'>
<span class="A">I am</span>
<span class="B">working in </span>
<span class="C">ABC company.</span>
</p>
Run Code Online (Sandbox Code Playgroud)
当用户单击该按钮时,该内容<p id='txt'>
将成为以下内容
预期结果:
<p id='txt'>
// All the HTML element within the <p> will be disappear
I am working in ABC company.
</p>
Run Code Online (Sandbox Code Playgroud)
任何人都可以帮我如何编写javascript函数?谢谢.
Gab*_*aru 198
你可以用这个:
var element = document.getElementById('txt');
var text = element.innerText || element.textContent;
element.innerHTML = text;
Run Code Online (Sandbox Code Playgroud)
根据您的需要,您可以使用element.innerText
或element.textContent
.它们在很多方面有所不同.innerText
尝试估计如果你选择你所看到的(渲染的html)并将其复制到剪贴板会发生什么,而textContent
只是剥离html标签并给你剩下的东西.
innerText
也具有与旧IE浏览器的兼容性(来自那里).
jco*_*ctx 68
[2017-07-25]因为这仍然是一个公认的答案,尽管是一个非常hacky的解决方案,我将Gabi的代码融入其中,留下我自己作为一个坏榜样.
<style>
.A {background: blue;}
.B {font-style: italic;}
.C {font-weight: bold;}
</style>
<script>
// my hacky approach:
function get_content() {
var html = document.getElementById("txt").innerHTML;
document.getElementById("txt").innerHTML = html.replace(/<[^>]*>/g, "");
}
// Gabi's elegant approach, but eliminating one unnecessary line of code:
function gabi_content() {
var element = document.getElementById('txt');
element.innerHTML = element.innerText || element.textContent;
}
// and exploiting the fact that IDs pollute the window namespace:
function txt_content() {
txt.innerHTML = txt.innerText || txt.textContent;
}
</script>
<input type="button" onclick="get_content()" value="Get Content (bad)"/>
<input type="button" onclick="gabi_content()" value="Get Content (good)"/>
<input type="button" onclick="txt_content()" value="Get Content (shortest)"/>
<p id='txt'>
<span class="A">I am</span>
<span class="B">working in </span>
<span class="C">ABC company.</span>
</p>
Run Code Online (Sandbox Code Playgroud)
Sar*_*ath 24
如果你可以使用jquery那么简单
$("#txt").text()
Run Code Online (Sandbox Code Playgroud)
Jam*_*mes 10
这个答案将只用于获取任何HTML元素的文本.
第一个参数"node"是从中获取文本的元素.第二个参数是可选的,如果为true,则在元素中的文本之间添加空格,否则在那里不存在空格.
function getTextFromNode(node, addSpaces) {
var i, result, text, child;
result = '';
for (i = 0; i < node.childNodes.length; i++) {
child = node.childNodes[i];
text = null;
if (child.nodeType === 1) {
text = getTextFromNode(child, addSpaces);
} else if (child.nodeType === 3) {
text = child.nodeValue;
}
if (text) {
if (addSpaces && /\S$/.test(result) && /^\S/.test(text)) text = ' ' + text;
result += text;
}
}
return result;
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
235924 次 |
最近记录: |