javascript - 从变量内的 html 字符串中选择元素

标签 javascript jquery html

我在变量中有 html 字符串数据,如下所示

 var htmlstring = "<div><div class='testdiv'>924422</div></div>"

我期望的是获取具有类的 div 的内容。在此示例中为 .testdiv 数据。

我怎样才能实现?

我知道一种方法:将此 html 字符串附加到 html 页面,然后访问。但我不想这样做,因为我正在使用 ajax 和服务器返回某种 html 字符串。现在我想获取特定内部的数据分区。

那么还有什么替代方法吗?

最佳答案

首先,您不要在 html 中的类名中使用 . 。要获取 html 字符串中该 div 的内容,您可以使用 jquery find 函数。

var htmlstring = "<div><div class='testdiv'>924422</div></div>"
alert($(htmlstring).find('.testdiv').html());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

关于javascript - 从变量内的 html 字符串中选择元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46735592/

相关文章:

javascript - .load() 适用于 IE 和 Dreamweaver 预览版,但不适用于 Opera 和 chrome

jquery - 在 WebAPI 中进行 POST 调用时,请求的资源不支持 http 方法 'GET"

asp.net - IE7 中的 DropDownList BackColor

包中包含的 Java 小程序

html - 为什么输入和按钮没有占据 div 的整个宽度?

javascript - 为什么 qUnit 的 assert.equal 认为这两个字符串在 IE 中是不同的?

javascript - 对 Bootstrap 模态使用不同的 Angular Controller

javascript - 移动 HTML5 应用程序 - 确定用户的日期/时间偏好?

javascript - 如何将按钮值传递给模态弹出 View ?

javascript - hasClass 不起作用