我正在尝试从 HTML 正文内容中获取所有引号。 目前我处于这种状态:
<!DOCTYPE html>
<html>
<body>
<p id="demo">
<pre> This is my text "with some quotes" and some "more" quotes. </p>
<button type="button" onclick="myFunction()">Get quotes</button>
<script>
function myFunction() {
var text = document.body.innerHTML;
var quotes =text.match(/"([^"]+)"/g);
for (var i = 0; i < quotes.length; i++) {
document.write(quotes[i] + "<br />" + "<br />");
}
}
</script>
</body>
</html>
但是我得到了代码中的所有引号,如下所示: “演示”
"with some quotes"
"more"
"button"
"myFunction()"
"([^"
"/g); for (var i = 0; i < quotes.length; i++) { document.write(quotes[i] + "
" + "
当我真的只需要这个时:
"with some quotes"
"more"
你有什么想法可以解决这个问题吗? 我尝试将内容直接写入 var text 并且一切正常,但是我想自动将内容从正文中取出。 我们将不胜感激您的建议。
最佳答案
你可以改变
var text = document.body.innerHTML;
至
var text = document.body.innerText;
从内容中检索而不包含 HTML
编辑:如果您无法使用 jQuery,您可能希望使用innerText 和textContent 属性的组合来获得更跨浏览器友好的解决方案。 示例:http://help.dottoro.com/ljhvexii.php
<小时/>更新:此答案于 2014 年提交。现在几乎所有浏览器都支持 innerText
:
- IE 6+
- Edge 所有版本
- Firefox 45+
- Chrome 4+
- Safari 3.2+
- 歌剧 10+
更多浏览器信息位于caniuse.com
关于javascript - 如何使用javascript获取HTML正文的内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25273321/