我正在将一个HTML页面拉到包含各种标签(img,div等)的服务器上.
I'm pulling a HTML page a server which contains various tags (img, div etc.).
在客户端,我将其插入div中,以使其完全像html文件一样显示.它可能包含图像和文本.但是有时有些img标签的src具有相对路径.
On the client side, I'm inserting this into a div so that it is getting displayed exactly like the html file. It may contain images and text. But sometimes there are img tags whose src has a relative path.
如何识别这些未引用完整http/https(绝对路径)而是以"/"开头的img标签,以标识它是相对的?
How can I identify these img tags which don't reference a full http/https (absolute path) but rather start with "/" so as to identify that it is relative?
推荐答案
- 您可以使用 .find() 方法来检查div是否包含img
- 您可以使用 .attr() 方法来获取src
- You can use .find() method to check if the div contains img
- You can use .attr() method to grab the src
您可以使用字符串函数/正则表达式检查src属性是否以http,https或/开头并相应地进行更改.
You can use string functions/regex to check if src attribute begins with http, https or / and change it accordingly.
示例:
$("#div1").find("img").length // returns the number of images inside #div1 $("#div1").find("img").each(function () { var src = $(this).attr("src"); // grab the src "attribute" console.log(src); console.log(src.indexOf("/") == 0); // true -> starts with / console.log(src.indexOf("") == 0); // true -> starts with console.log(src.indexOf("") == 0); // true -> starts with });更多推荐
如何检查DIV是否包含带有相对src路径的IMG标签?
发布评论