通过js修改html的标签属性

      在开发一个详情页面时,通过调用iOS的UIWebView进行内容展示,本来很顺利的事情,却因为Safari的问题,有的页面图片加载不出来,甚是郁闷。于是把一个能加载图片的html源码和一个不能加载图片的html源码进行分析对比,发现是img标签里面多了一个data-src属性。

     百度了一下data-src,找到相关信息:

追过html5.
刚刚查资料看了一下
Sets or retrieves the identifier of the data source that is bound to the element.In HTML, only Internet Explorer supports table creation dynamically from XML. If you want to implement similar functionality in other browsers, you need to use JavaScript. For further details, see the page for the XMLHttpRequest object.
大体的意思是:
设置或检索数据源绑定到元素的标识符。
我查看了好几个例子,主要的应用是在延迟加载,把图片延迟加载,当浏览到的时候读取data-src,然后他就自动引导到src这个属性,可能说的不太正确,大体是这个意思。但是你要明确图片路径时还是用src而不是data-src

      反正不管是什么原因,先把它去掉试试,刚开始想到的是用匹配的方法,直接替换掉,这是比较熟悉的方式。但是一想到要对一大段的html慢慢算NSRange,就犯难了。于是想到用第三方库,把节点都提取出来,就不用自己慢慢精确地计算位置了。但回头一想,为这么个小问题,加个库不值当啊,就想到了js。在刚开始写js的时候,因为都没写过,也不太会调试方法,搞了很久,都没什么效果,而且还用了jQ里面的设置属性的方法,而我只能在客户端加一段js,没有jQ环境,最终只能作罢,还是用老方法吧,难是难点,但是能解决燃眉之急。

于是有了以下代码:

NSString *searchText = [NSMutableString stringWithString:html];
    
    NSError *error;
    NSString *regulaStr = @"<img[^>]+>";
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regulaStr
                                                                           options:NSRegularExpressionCaseInsensitive
                                                                             error:&error];
    NSArray *arrayOfAllMatches = [regex matchesInString:searchText options:0 range:NSMakeRange(0, [searchText length])];
    
    NSMutableArray *exchangeStrArr = [NSMutableArray array];
    for (NSTextCheckingResult *match in arrayOfAllMatches)
    {
        NSString* substringForMatch = [searchText substringWithRange:match.range];
        
        NSRange subRange = [substringForMatch rangeOfString:@"src=\"?(.*?)(\"|>|\\s+)" options:NSRegularExpressionSearch];
        NSString *resultStr = @"";
        if (subRange.location != NSNotFound) {
            NSString *src = [substringForMatch substringWithRange:subRange];
            resultStr = [NSString stringWithFormat:@"<img style=\"box-sizing: border-box; width: 100%%; height: auto !important;\" %@ />", src];
        }
        NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:substringForMatch, @"original", resultStr, @"new", nil];
        [exchangeStrArr addObject:dic];
    }
    
    for (int i=0; i<exchangeStrArr.count; i++) {
        NSDictionary *item = [exchangeStrArr objectAtIndex:i];
        NSString *original = [item objectForKey:@"original"];
        NSString *new = [item objectForKey:@"new"];
        searchText = [searchText stringByReplacingOccurrencesOfString:original withString:new];
    }
    
    webview.html = searchText;

这一看就不甚优雅啊。但是项目能上传了。。。

第二天,赶完项止睡饱觉,就考虑做得优雅一点了,毕竟这是程序员的一大追求。因为前一天坑了那么久,而且也睡够了,灵感爆发,用web检查器检查js处理后的html元素时发现这个图片是因为src这个属性值在Safari打不开图片,而data-src的值却是能打开的,于是一下就做出来了,于是有了以下代码:

 var items = document.getElementsByTagName("img");
 for(var i = 0;i<items.length;i++){
   var imgDataSrc = items[i].getAttribute('data-src');
   if (imgDataSrc) {
     items[i].setAttribute('src', imgDataSrc);
     items[i].removeAttribute('data-src');
   };
 }

但再想深一层,这段代码还是太粗暴了点,能不能温柔点呢?百度一下『js判断图片是否存在』,发现还真有onerror这个属性,是在图片加载不出来时的执行内容,于是写了以下代码:

var items = document.getElementsByTagName("img");
for(var i = 0;i<items.length;i++){
  items[i].setAttribute('onerror', 'javascript:var imgDataSrc = this.getAttribute(\'data-src\'); if (imgDataSrc) {this.setAttribute(\'src\', imgDataSrc);this.removeAttribute(\'data-src\')};');
}

恩,到这里对一些正常显示的网页影响就更小了,到此为止,是我想到的比较好的解决方式,如果看到的网友有更好的想法,请不吝指教!

最后的结果就是以下,用NSString方法在html上加入一段js

html = [html stringByAppendingString:@"<script>\
            var items = document.getElementsByTagName(\"img\");\
            for(var i = 0;i<items.length;i++){\
                items[i].setAttribute('onerror', 'javascript:var imgDataSrc = this.getAttribute(\\'data-src\\'); if (imgDataSrc) {this.setAttribute(\\'src\\', imgDataSrc);this.removeAttribute(\\'data-src\\')};');\
            }\
            </script>"];
  
<head>
    <meta name="viewport" content="width=300.000000,inital-scale=1.0,maximum-scale=1.0,user-scalable=no;"
    />
    <style type="text/css">
      body {font-family: "黑体"; font-size: 14px;padding:0px;margin:0px;} p{font-size:14px;line-height:
      1.5em;} img{ width:300.000000;margin:0;padding:0;} span{font-size:14px;}
    </style>
  </head>
  
  <body>
    <div id="webview_content_wrapper">
      <p style="white-space: normal;">
        <span style="font-size: 14px; line-height: 1.5em;">
          魔都的夜生活从来都不乏味,哪个场子都能闻到动物派对出没的味道,烟酒味、香水味,都是捕猎的信号,没有多少年轻人愿意数着脚趾眼巴巴地独自到天亮。
        </span>
        <br/>
      </p>
      <p style="white-space: normal;">
        <br style="margin: 0px; padding: 0px; max-width: 100%; box-sizing: border-box !important; word-wrap: break-word !important;"
        />
      </p>
      <p style="white-space: normal; line-height: 1.5em;">
        <span style="font-size: 14px;">
          直到躁来躁去好像都是一样的劲儿,舞池里新鲜的只有姑娘身上从不重样的衣服,疯狂的舞步跳到熟悉,好像缺了些刺激。
          <br style="margin: 0px; padding: 0px; max-width: 100%; box-sizing: border-box !important; word-wrap: break-word !important;"
          />
        </span>
      </p>
      <p style="white-space: normal;">
        <br style="margin: 0px; padding: 0px; max-width: 100%; box-sizing: border-box !important; word-wrap: break-word !important;"
        />
      </p>
      <p style="white-space: normal; line-height: 1.5em;">
        <span style="font-size: 14px;">
          如果你还对「新鲜」依旧敏感,我们给你准备了一个充满无限可能的派对。上海的夜晚经得起一闹再闹,欢迎各种味道。当然,少不了你的份。
        </span>
      </p>
      <p style="white-space: normal; line-height: 1.5em;">
        <span style="font-size: 14px;">
          <br/>
        </span>
      </p>
      <p style="white-space: normal; line-height: 1.5em;">
        <span style="font-size: 14px;">
          <br/>
        </span>
      </p>
      <p style="white-space: normal; text-align: center;">
        <strong>
          Stage+ Launch Party | Shanghai 上海站&nbsp;
        </strong>
      </p>
      <p style="white-space: normal; text-align: center;">
        <strong>
          时间&nbsp;Data:2016.3.30 &nbsp;周三21:00~深夜 &nbsp;
        </strong>
      </p>
      <p style="white-space: normal; text-align: center;">
        <strong>
          地点&nbsp;Address:上海 Arkham 徐汇区乌鲁木齐南路1号&nbsp;
        </strong>
      </p>
      <p style="white-space: normal; text-align: center;">
        <strong>
          &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;No.1&nbsp;South&nbsp;Wulumuqi &nbsp;Road,
          Shanghai
        </strong>
      </p>
      <p style="white-space: normal; text-align: center;">
        <strong>
          票价&nbsp;Price:¥100
        </strong>
      </p>
      <p style="white-space: normal;">
        <br/>
      </p>
      <p style="white-space: normal;">
        <br/>
      </p>
      <p style="white-space: normal; text-align: center;">
        <strong>
          阵容介绍
          <br style="margin: 0px; padding: 0px; max-width: 100%; box-sizing: border-box !important; word-wrap: break-word !important;"
          />
        </strong>
      </p>
      <p style="white-space: normal; text-align: center;">
        <strong>
          DJ Lineup
        </strong>
      </p>
      <p style="white-space: normal;">
        <strong>
          <br/>
        </strong>
      </p>
      <p style="white-space: normal;">
        <br/>
      </p>
      <p style="white-space: normal; text-align: center;">
        <strong>
          Jack Beats&nbsp;
        </strong>
      </p>
      <p style="white-space: normal; text-align: center;">
        <strong>
          两个世界冠军对你的耳膜进行碾压
        </strong>
      </p>
      <p style="white-space: normal;">
        <br style="margin: 0px; padding: 0px; max-width: 100%; box-sizing: border-box !important; word-wrap: break-word !important;"
        />
      </p>
      <p style="white-space: normal; text-align: center;">
        <img data-s="300,640" data-type="jpeg" data-ratio="1" data-w="" width="auto"
        data-src="http://mmbiz.qpic.cn/mmbiz/NZ8IXO0DxLicV9iah30Jo8ST92icyWG5bZXFvy9he8iaxTPSNrWK0RwWAORsx5w0EQnQ7cXEbF9OypTWafwDm0zcKA/640?wx_fmt=jpeg"
        _width="auto" src="http://mmbiz.qpic.cn/mmbiz/NZ8IXO0DxLicV9iah30Jo8ST92icyWG5bZXFvy9he8iaxTPSNrWK0RwWAORsx5w0EQnQ7cXEbF9OypTWafwDm0zcKA/640?wx_fmt=jpeg&tp=webp&wxfrom=5&wx_lazy=1"
        style="margin: 0px; padding: 0px; max-width: 100%; height: auto !important; box-sizing: border-box !important; word-wrap: break-word !important; width: auto !important; visibility: visible !important;"
        />
        <br style="margin: 0px; padding: 0px; max-width: 100%; box-sizing: border-box !important; word-wrap: break-word !important;"
        />
      </p>
      <p style="white-space: normal;">
        <br style="margin: 0px; padding: 0px; max-width: 100%; box-sizing: border-box !important; word-wrap: break-word !important;"
        />
      </p>
      <p style="white-space: normal;">
        <br/>
      </p>
      <p>
      </p>
      <section style="white-space: normal;">
        <section>
          <section>
            <section>
              <section>
                <section>
                  <section>
                    <p style="line-height: 1.5em;">
                      <span style="font-size: 14px;">
                        来自伦敦的Jack Beats是一个拥有疯狂历史的老练组合。这个二人组由Scratch Perverts的DJ Plus One和Mixologists的Beni
                        G组成,Plus One在他20岁的时候击败了Kentaro和Klever这样强劲的对手从而成为英国1989以来第一位DMC世界冠军。Beni
                        G也是前DMC &amp; ITF DJ冠军和两届城市音乐奖的得主。
                      </span>
                    </p>
                    <p style="line-height: 1.5em;">
                      <span style="font-size: 14px;">
                        Jack Beats作为两人的合作项目,将重心更多的放在制作领域。音乐类型上也大步跨越,吸收Electro, Hip-hop, Drum n
                        bass, Dubstep等等音乐元素,时髦混搭出极具前瞻性与煽动力的舞池炸弹。
                      </span>
                    </p>
                    <p>
                      <br style="margin: 0px; padding: 0px; max-width: 100%; box-sizing: border-box !important; word-wrap: break-word !important;"
                      />
                    </p>
                    <p>
                      <br/>
                    </p>
                    <p style="line-height: 1.5em;">
                      <span style="font-size: 14px;">
                        After almost a decade together, Niall Dailly and Ben Geffin’s mission
                        statement remain slargely the same as it did since they combined forces
                        in 2007 to be on the front line of inventive, forward thinking house music.&nbsp;
                      </span>
                    </p>
                    <p style="line-height: 1.5em;">
                      <span style="font-size: 14px;">
                        While Jack Beats’sound is hard to pin down, it is one that was initially
                        heavily influenced by their hometown of London. The duo’s output is a reflection
                        of their love of hybrid music, and wide-ranging influences from hip-hop
                        to house to drum ‘n’bass.
                      </span>
                    </p>
                    <p style="line-height: 1.5em;">
                      <span style="font-size: 14px;">
                        Over the past few years, Jack Beats have managed to amass a dedicated
                        international following of their thunderous bass-heavy approach to house
                        music, aided by a string of monstrous remixes for the likes of Beyonce,
                        Major Lazer, Florence &amp; The Machine,&nbsp;Diploand Rudimental. Renowned
                        as world-class DJs, Jack Beats have graced many&nbsp;of the world’s most
                        important DJ booths and festivals including Coachella, Fuji Rocks,Glastonbury,
                        EDC and Sonar, as well as having released on labels such as OWSLA,Rinse,
                        Nightbass and Columbia.
                      </span>
                    </p>
                  </section>
                </section>
              </section>
            </section>
          </section>
        </section>
      </section>
      <p>
      </p>
      <p style="white-space: normal;">
        <br/>
      </p>
      <p style="white-space: normal;">
        <br style="margin: 0px; padding: 0px; max-width: 100%; box-sizing: border-box !important; word-wrap: break-word !important;"
        />
      </p>
      <p style="white-space: normal; text-align: center;">
        <strong>
          3ASiC
        </strong>
      </p>
      <p style="white-space: normal; text-align: center;">
        <strong>
          他五年级时就拿到了国家计算机二级(VB)的证书
        </strong>
      </p>
      <p style="white-space: normal; text-align: center;">
        &nbsp;
        <img data-s="300,640" data-type="jpeg" data-ratio="1" data-w="" data-src="http://mmbiz.qpic.cn/mmbiz/NZ8IXO0DxL8g4knJHibnygaChgr1kbkhy1gctLqrGbRVbFPBJj9sZlSUpYF9oDIDqpp9RsGvAW5detE7jrRJbHQ/640?wx_fmt=jpeg"
        _width="auto" src="http://mmbiz.qpic.cn/mmbiz/NZ8IXO0DxL8g4knJHibnygaChgr1kbkhy1gctLqrGbRVbFPBJj9sZlSUpYF9oDIDqpp9RsGvAW5detE7jrRJbHQ/640?wx_fmt=jpeg&tp=webp&wxfrom=5&wx_lazy=1"
        style="margin: 0px; padding: 0px; max-width: 100%; height: auto !important; box-sizing: border-box !important; word-wrap: break-word !important; width: auto !important; visibility: visible !important;"
        />
        <br style="margin: 0px; padding: 0px; max-width: 100%; box-sizing: border-box !important; word-wrap: break-word !important;"
        />
      </p>
      <p style="white-space: normal;">
        <br style="margin: 0px; padding: 0px; max-width: 100%; box-sizing: border-box !important; word-wrap: break-word !important;"
        />
      </p>
      <p style="white-space: normal;">
        <br/>
      </p>
      <p>
      </p>
      <section style="white-space: normal;">
        <section>
          <section>
            <section>
              <section>
                <section>
                  <section>
                    <p style="line-height: 1.5em;">
                      <span style="font-size: 14px;">
                        伍子轩(3ASiC ),2014年以优秀的专业成绩毕业于南京艺术学院传媒学院录音系,现任知乎日报电子音乐专栏编辑。他是来自南京的DJ、音乐制作人,同步计划电子音乐厂牌主理人,国内低音音乐与电子舞曲代表人物之一。已在iTunes、Beatport等国外各大音乐售卖网站发行多首单曲以及两张EP,目前主要致力于低音音乐的制作,这个国内新生代的电子音乐制作人将会跟随着周三巡演的脚步,在上海成都和广州都能看到他的身影。
                      </span>
                    </p>
                    <p>
                      <br style="margin: 0px; padding: 0px; max-width: 100%; box-sizing: border-box !important; word-wrap: break-word !important;"
                      />
                    </p>
                    <p style="line-height: 1.5em;">
                      <span style="font-size: 14px;">
                        3ASiC, a DJ/Producer from Nanjing, also a co-founder and manager of Project
                        Sync Records, is a risingstar of Chinese bass music scene. He has released
                        several singles and EPs on online stores includingi Tunes and Beatport.
                      </span>
                    </p>
                    <p style="line-height: 1.5em;">
                      <span style="font-size: 14px;">
                        3ASiC is a professional music producer and sound engineer, who has a unique
                        and thorough conceptfor sound design and producing, which can be easily
                        seen from his live performances. Meanwhile, 3ASiC as the core leader of
                        Project Sync Records, has been leading a group of brilliant producers in
                        China andconstantly releasing excellent works on Project Sync label. Lately
                        3ASiC was also elected as the chiefeditor of Zhihu Daily music section,
                        aiming to boost the development of electronic music industry within China.
                      </span>
                    </p>
                  </section>
                </section>
              </section>
            </section>
          </section>
        </section>
      </section>
      <p>
      </p>
      <p style="white-space: normal;">
        <br/>
      </p>
      <p style="white-space: normal;">
        <br style="margin: 0px; padding: 0px; max-width: 100%; box-sizing: border-box !important; word-wrap: break-word !important;"
        />
      </p>
      <p style="white-space: normal; text-align: center;">
        <strong>
          DJ Verse@ille&nbsp;
        </strong>
      </p>
      <p style="white-space: normal; text-align: center;">
        <strong>
          南非驻中国电音大使
        </strong>
      </p>
      <p style="white-space: normal;">
        <br style="margin: 0px; padding: 0px; max-width: 100%; box-sizing: border-box !important; word-wrap: break-word !important;"
        />
      </p>
      <p style="white-space: normal; text-align: center;">
        <img data-s="300,640" data-type="jpeg" data-ratio="1.5" data-w="360" width="auto"
        data-src="http://mmbiz.qpic.cn/mmbiz/NZ8IXO0DxLicV9iah30Jo8ST92icyWG5bZXjpxV9cU3ETB5bnpD6cZXw2cDjj4r5tKODIKDbERAPhuysiafMk3LSQg/640?wx_fmt=jpeg"
        _width="auto" src="http://mmbiz.qpic.cn/mmbiz/NZ8IXO0DxLicV9iah30Jo8ST92icyWG5bZXjpxV9cU3ETB5bnpD6cZXw2cDjj4r5tKODIKDbERAPhuysiafMk3LSQg/640?wx_fmt=jpeg&tp=webp&wxfrom=5&wx_lazy=1"
        style="margin: 0px; padding: 0px; max-width: 100%; height: auto !important; box-sizing: border-box !important; word-wrap: break-word !important; width: auto !important; visibility: visible !important;"
        />
        <br style="margin: 0px; padding: 0px; max-width: 100%; box-sizing: border-box !important; word-wrap: break-word !important;"
        />
      </p>
      <p style="white-space: normal;">
        <br style="margin: 0px; padding: 0px; max-width: 100%; box-sizing: border-box !important; word-wrap: break-word !important;"
        />
      </p>
      <p style="white-space: normal;">
        <br/>
      </p>
      <p>
      </p>
      <section style="white-space: normal;">
        <section>
          <section>
            <section>
              <section>
                <section>
                  <p style="line-height: 1.5em;">
                    <span style="font-size: 14px;">
                      12年的DJ经历早已使DJ Verse@ille成为南非最顶级的DJ之一,频繁的来往于世界各国送上精彩的DJ现场表演,他的足迹遍布美国、英国、泰国、中国、澳大利亚、柬埔寨、马尔代夫、越南与南非。从小型的特色酒吧到大型的国际俱乐部现场、千人组成的盛大gala音乐节现场演出,到国际电台的混音现场,他都能驾驭的游刃有余。2010年他更被南非驻中国上海领事馆选为DJ代表,参与2010年上海世博会南非馆的音乐演出,曾多次参加中国的迷笛音乐节。
                    </span>
                  </p>
                  <p>
                    <br style="margin: 0px; padding: 0px; max-width: 100%; box-sizing: border-box !important; word-wrap: break-word !important;"
                    />
                  </p>
                  <p style="line-height: 1.5em;">
                    <span style="font-size: 14px;">
                      Originally hailing from South Africa, Verse@ille has firmly established
                      himself as one of Shanghai&#39;s most in demand party DJs, bringing his
                      flawless turntable skills to over 100 clubs throughout the city. His seamless
                      blending of styles &nbsp;(Hip-Hop, R&amp;B, Funk, Trap, Twerk, Moombahton,
                      Dancehall, Dubstep, Kwaito) and his personality in the DJ booth has earned
                      him spots at major local and international festivals, and also made him
                      a favourite on the airwaves all over the world.
                      <br style="margin: 0px; padding: 0px; max-width: 100%; box-sizing: border-box !important; word-wrap: break-word !important;"
                      />
                      He even uses his skills for charity work with his MAD (Making A Difference)
                      endeavours as part of his Verse@illity Entertainment brand.
                    </span>
                  </p>
                  <p>
                    <br/>
                  </p>
                  <p>
                    <br/>
                  </p>
                </section>
              </section>
            </section>
          </section>
        </section>
      </section>
      <p>
      </p>
      <p style="white-space: normal; line-height: 1.5em;">
        <span style="font-size: 14px;">
          有一种奇葩的病叫ADD,
        </span>
      </p>
        <strong>
          <span style="font-size: 14px;">
            病征为大部分时间精神涣散,
          </span>
        </strong>
      </p>
      <p style="white-space: normal; line-height: 1.5em;">
        <strong>
          <span style="font-size: 14px;">
      <p style="white-space: normal; line-height: 1.5em;">
            全名为Attention Deficit Disorder(注意力不足过动症),
          </span>
        </strong>
      </p>
      <p style="white-space: normal; line-height: 1.5em;">
            极个别时间精神超长集中,
        <strong>
          <span style="font-size: 14px;">
          </span>
        </strong>
      </p>
      <p style="white-space: normal; line-height: 1.5em;">
        <span style="font-size: 14px;">
          ADD晚期患者,不单是你,也加我一个,音乐是你我的良药。
        </span>
      </p>
      <p style="white-space: normal; line-height: 1.5em;">
        <span style="font-size: 14px;">
          一大波搭救ADD患者的音乐派对正奔赴路上,这是病,得治!
        </span>
      </p>
    </div>
    <div id="bottom_holder">
    </div>
  </body>

</html>

<script>
//方法1:适应性更强
var items = document.getElementsByTagName("img");
for(var i = 0;i<items.length;i++){
  items[i].setAttribute('onerror', 'javascript:var imgDataSrc = this.getAttribute(\'data-src\'); if (imgDataSrc) {this.setAttribute(\'src\', imgDataSrc);this.removeAttribute(\'data-src\')};');
}

//方法2
// var items = document.getElementsByTagName("img");
// for(var i = 0;i<items.length;i++){
//   var imgDataSrc = items[i].getAttribute('data-src');
//   if (imgDataSrc) {
//     items[i].setAttribute('src', imgDataSrc);
//     items[i].removeAttribute('data-src');
//   };
// }
</script>
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值