javascript - 如何使用 javascript 或 jquery 从字符串中提取 html 标签的内容?

标签 javascript jquery html

<分区>

也许这是非常基本的,但我很困惑。 我有一个包含许多部分 (div) 的简单 html 页面。我在 javascript 中有一个包含 html 标签的字符串。代码如下:

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript">
var str1="<html><body><div id='item1'><h2>This is a heading1</h2><p>This is a paragraph1.</p></div><div id='item2'><h2>This is a heading2</h2><p>This is another paragraph.</p></div><div id='lastdiv'>last</div></body></html>";
</script>
</head>
<body>
<div id="title1"></div>
<div id="new1"></div>
<div id="title2"></div>
<div id="new2"></div>
</body>
</html>

我想提取 html 标签的内容(从 javascript 中的字符串)并在我的 html 页面中的所需部分显示该内容。

即我希望在 <div id="title1"> 中显示“This is a heading1”和“这是段落1”。显示在<div id="new1">第二对标签也一样。

我需要所有这些只在客户端工作。我曾尝试使用 HTML DOM getElementByTagName 方法,但它变得太复杂了。我对 jquery 知之甚少。我很困惑。我不知道该怎么做。你能指导我使用什么 - javascript 或 jquery 以及如何使用它吗?有没有办法从字符串中识别并遍历它?

如何从 str1 中提取“This is heading1”(以及包含在 html 标签中的类似内容)?我不知道这些索引,因此不能在 javascript 中使用 substr() 或 substring() 函数。

最佳答案

使用 .text()作为“getter”和“setter”,我们可以重复以下模式:

  • 定位我们要填充的页面上的元素
  • 给它内容来自 字符串

jsFiddle

<script type="text/javascript">
var str1="<html><body><div id='item1'><h2>This is a heading1</h2><p>This is a paragraph1.</p></div><div id='item2'><h2>This is a heading2</h2><p>This is another paragraph.</p></div><div id='lastdiv'>last</div></body></html>";
$(function(){
    var $str1 = $(str1);//this turns your string into real html 

    //target something, fill it with something from the string
    $('#title1').text( $str1.find('h2').eq(0).text() );
    $('#new1').text( $str1.find('p').eq(1).text() );
    $('#title2').text( $str1.find('h2').eq(1).text() );
    $('#new2').text( $str1.find('p').eq(1).text() );
})
</script>

关于javascript - 如何使用 javascript 或 jquery 从字符串中提取 html 标签的内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9189338/

相关文章:

javascript - 外部依赖项错误地捆绑在 rollup.js 中?

javascript - 在 jQuery 中加载后关闭子窗口

javascript - 拖放多个文件上传到单个文件上传

jquery - 使用 jQuery (.animate) 和 KineticJS 框架调整 Canvas 大小

javascript - Monaco Editor 在空行上显示字符

javascript - 如何在滚动条上改变div宽度

javascript - 如何使用正则表达式获取字符串末尾的数字后跟此字符 `:`

javascript - 获取隐藏类型值的 span id 值

javascript - ES5 定义不可更改的数组/属性值

javascript - 使用 WebGL 上下文阻止 Canvas 中的右键单击