在不请求图像的情况下将HTML字符串加载到jQuery中 [英] load an HTML string into jQuery without requesting images

查看:75
本文介绍了在不请求图像的情况下将HTML字符串加载到jQuery中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在不请求图片的情况下将包含图像标签的HTML字符串加载到jQuery中?我希望能够在jQuery对象上运行选择器来提取一些信息。采用以下示例:

  var string = $('< p>< img src =http:// image .url / file.jpg/>< / p>'); 
string.find('img');

浏览器将发出 HTTP://image.url/file.jpg 。我试图找到一种方法来做同样的事情,但没有浏览器请求图像。



谢谢

  function searchXml(xmlStr,selector){
var parser,xmlDoc;
if(window.DOMParser){
parser = new DOMParser();
xmlDoc = parser.parseFromString(xmlStr,text / xml);
} else {
xmlDoc = new ActiveXObject(Microsoft.XMLDOM);
xmlDoc.async = false;
xmlDoc.loadXML(xmlStr);
}
返回$(xmlDoc).find(selector);
}

console.log(searchXml('< p>< img src =http://image.url/file.jpg/>< / p> ','img')。attr('src'));

查看在行动: http://jsfiddle.net/na9Tt/



Keep记住它是一个XML文档,而不是HTML文档,因此某些特定于HTML的特定类型的搜索可能无法以完全相同的方式工作。


Is there a way to load an HTML string that contains image tags into jQuery without requesting the images? I want to be able to run selectors on the jQuery object to extract some information. Taking the following example:

var string = $('<p><img src="http://image.url/file.jpg" /></p>');
string.find('img');

The browser will make a request for http://image.url/file.jpg. I'm trying to find a way to do the same but without the browser making a request for the image.

Thanks

解决方案

You can use an XML document to perform the search:

function searchXml(xmlStr, selector) {
    var parser, xmlDoc;
    if(window.DOMParser) {
        parser = new DOMParser();
        xmlDoc = parser.parseFromString(xmlStr, "text/xml");
    } else {
        xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
        xmlDoc.async = false;
        xmlDoc.loadXML(xmlStr); 
    }
    return $(xmlDoc).find(selector);
}

console.log(searchXml('<p><img src="http://image.url/file.jpg" /></p>', 'img').attr('src'));​​​​

See it in action: http://jsfiddle.net/na9Tt/

Keep in mind it is an XML document, not an HTML document, so some particular types of searches which are specific to HTML may not work exactly the same way.

这篇关于在不请求图像的情况下将HTML字符串加载到jQuery中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆