如何检查DIV是否包含带有相对src路径的IMG标签? [英] How can I check if a DIV contains IMG tags with relative src paths?

查看:265
本文介绍了如何检查DIV是否包含带有相对src路径的IMG标签?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将一个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属性是否以httphttps/开头并相应地进行更改.

      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("http://") == 0);  // true -> starts with http://
          console.log(src.indexOf("https://") == 0); // true -> starts with https://
      });
      

      这篇关于如何检查DIV是否包含带有相对src路径的IMG标签?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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