用jQuery解析HTML字符串 [英] parse html string with jquery
问题描述
我有一个来自Ajax加载源的HTML字符串.在将HTML放入文档中之前,我想从该字符串中的对象(图像)中获取一些属性.
I have an HTML string from a Ajax loaded source. I would like to get some attributes from an object (image) in this string, before I put the HTML into the document.
我有类似的东西:
$.ajax({
url: uri+'?js',
success: function(data) {
var htmlCode = $(data).html();
$('#otherObject').html(data);
}
});
如何从该HTML字符串获取属性(例如src
)?
How can I get attributes (the src
for example) from this HTML string?
推荐答案
我不确定100%,但不会
I'm not a 100% sure, but won't
$(data)
为该数据生成一个带有DOM的jquery对象,该对象未连接到任何地方?或者,如果已经将其解析为DOM,则可以只使用$(#myImg",data)或任何适合您需要的选择器.
produce a jquery object with a DOM for that data, not connected anywhere? Or if it's already parsed as a DOM, you could just go $("#myImg", data), or whatever selector suits your needs.
编辑
重新阅读您的问题,看来您的数据"已经是一个DOM,这意味着您可以进行操作(假设DOM中只有一个img,否则您将需要一个更精确的选择器)
EDIT
Rereading your question it appears your 'data' is already a DOM, which means you could just go (assuming there's only an img in your DOM, otherwise you'll need a more precise selector)
$("img", data).attr ("src")
如果要访问src属性.如果您的数据只是文本,则可能可以做到
if you want to access the src-attribute. If your data is just text, it would probably work to do
$("img", $(data)).attr ("src")
这篇关于用jQuery解析HTML字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!