jQuery 用jquery解析html字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/704679/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
parse html string with jquery
提问by MarvinS
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 加载源的 HTML 字符串。在将 HTML 放入文档之前,我想从该字符串中的对象(图像)中获取一些属性。
I've got something like:
我有类似的东西:
$.ajax({
url: uri+'?js',
success: function(data) {
var htmlCode = $(data).html();
$('#otherObject').html(data);
}
});
How can I get attributes (the src
for example) from this HTML string?
如何src
从此 HTML 字符串获取属性(例如)?
回答by falstro
I'm not a 100% sure, but won't
我不是 100% 肯定,但不会
$(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 的 jquery 对象,而不是在任何地方连接?或者,如果它已经被解析为 DOM,你可以直接使用 $("#myImg", data) 或任何适合你需要的选择器。
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)
编辑
重新阅读你的问题,你的“数据”似乎已经是一个 DOM,这意味着你可以去(假设你的 DOM 中只有一个 img,否则你需要一个更精确的选择器)
$("img", data).attr ("src")
if you want to access the src-attribute. If your data is just text, it would probably work to do
如果你想访问 src 属性。如果您的数据只是文本,它可能会起作用
$("img", $(data)).attr ("src")
回答by MarvinS
MarvinS.-
马文S.-
Try:
尝试:
$.ajax({
url: uri+'?js',
success: function(data) {
var imgAttr = $("img", data).attr('src');
var htmlCode = $(data).html();
$('#imgSrc').html(imgAttr);
$('#fullHtmlOutput').html(htmlCode);
}
});
This should load the whole html block from data into #fullHtmlOutput and the src of the image into #imgSrc.
这应该将数据中的整个 html 块加载到 #fullHtmlOutput 中,并将图像的 src 加载到 #imgSrc 中。
回答by MarvinS
just add container element befor your img element just to be sure that your intersted element not the first one, tested in ie,ff
只需在 img 元素之前添加容器元素,以确保您感兴趣的元素不是第一个,在 ie,ff 中进行测试
回答by The Coder
One thing to note - as I had exactly this problem today, depending on your HTML jQuery may or may not parse it that well. jQuery wouldn't parse my HTML into a correct DOM - on smaller XML compliant files it worked fine, but the HTML I had (that would render in a page) wouldn't parse when passed back to an Ajax callback.
需要注意的一件事 - 因为我今天遇到了这个问题,这取决于您的 HTML jQuery 可能会也可能不会很好地解析它。jQuery 不会将我的 HTML 解析为正确的 DOM - 在较小的 XML 兼容文件上它运行良好,但是我拥有的 HTML(将在页面中呈现)在传递回 Ajax 回调时不会解析。
In the end I simply searched manually in the string for the tag I wanted, not ideal but did work.
最后,我只是在字符串中手动搜索我想要的标签,虽然不理想但确实有效。