使用jquery从HTML中提取属性

extracting attributes from html using jquery

本文关键字:提取 属性 HTML jquery 使用      更新时间:2023-09-26

我有一个字符串,我从outerHTML。日志如下:

var responseHtml = jQuery(data).find("#response")[0].outerHTML;
console.log(responseHtml);
Log:
<div id="response" hello="world" big="span" hey="there">&lt;'/div&gt;"
<div class="clear"></div></div>

我试图得到它的格式,所以我可以访问'世界',如:values["hello"] => "world"

我被困在这里了。实现这一目标的合适方法是什么?

您应该使用data属性,而不是创建无效属性,如:

<div id="response" data-hello="world" data-big="span" data-hey="there"></div>

然后用jquery获取这些值,你可以这样做:

var response = $('#response');
response.data('hello');  // returns "world"
response.data('big');  // returns "span"
response.data('hey'); // returns "there"

JS小提琴