【问题标题】:How can I check if a DIV contains IMG tags with relative src paths?如何检查 DIV 是否包含具有相对 src 路径的 IMG 标签?
【发布时间】:2013-03-14 08:44:25
【问题描述】:

我正在将一个 HTML 页面拉到一个包含各种标签(img、div 等)的服务器上。

在客户端,我将它插入到一个 div 中,以便它像 html 文件一样显示出来。它可能包含图像和文本。但有时也有 img 标签,其 src 有相对路径。

如何识别这些不引用完整 http/https(绝对路径)而是以“/”开头的 img 标签以识别它是相对的?

【问题讨论】:

    标签: jquery html image


    【解决方案1】:

    如果您用来显示它的 DIV 有一个标识符,那么您可以尝试使用

    获取该 div 的子元素
    $("#divID").children().find("img").each(function(){ 
        if(($(this).attr("src")).indexOf("PATH")>0) 
        { Do whatever.. } 
    });
    

    【讨论】:

      【解决方案2】:
      • 您可以使用.find()方法检查div是否包含img
      • 可以使用.attr()的方法来抓取src

      您可以使用字符串函数/正则表达式来检查src 属性是否以httphttps/ 开头并相应地进行更改。

      例子:

      $("#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://
      });
      

      【讨论】:

      • 嘿thnks。但我有1个疑问。如果src是相对的并将其附加到某个url。但是如何再次显示整个数据。没有得到:(
      • 即使我将其附加到 http,也不会显示具有相对路径的图像。
      猜你喜欢
      • 2014-01-01
      • 1970-01-01
      • 2015-10-02
      • 2018-07-13
      • 1970-01-01
      • 2013-10-25
      • 1970-01-01
      • 2013-10-22
      • 2014-01-20
      相关资源
      最近更新 更多