2017-07-25 76 views
-1

我想通过javascript为标记添加宽度和高度属性。 img src将来自网络(http://www....)。我使用javascript.replace来添加高度和宽度。这是我的代码。 (目前它只是宽度)。String.replace的超时

<!DOCTYPE html> 
<html> 

<body> 
    <script src="https://code.jquery.com/jquery-1.12.4.min.js"></script> 
    <script> 
    $(window).load(function() { 

     var htmlString = '<div class="sample"> <img src="https://kbob.github.io/images/sample-5.jpg"> </div><div class="sample_another"><img src="http://www.crazymonkeydefense.com/wp-content/uploads/2012/02/sample-img3.png"> </div> '; 

     function dostuff(img, imgString) { 
      img.onload = function() { 

       imgString = imgString.replace("<img ", '<img width="' + this.width + 'px" '); 
       console.log("modified = " + imgString); 
      }; 
     } 

     var modifyImg = function(imgString) { 
      console.log("original = " + imgString) 

      if (imgString.indexOf('width="') == -1) { 
       var newImgString = (imgString.substring(imgString.lastIndexOf('src="'), imgString.lastIndexOf('"'))).replace('src="', ''); 
       var img = new Image(); 
       img.src = newImgString; 
       dostuff(img, imgString); 
      } 
      return imgString; 
     } 

     modifiedHtmlString = htmlString.replace(/<img[^>]+>/g, modifyImg); 
     console.log(modifiedHtmlString); 


    }); 
    </script> 
</body> 

</html> 

与此问题是htmlString.replace(/] +> /克,modifyImg)此执行瞬间并设置ModifyImg值是未定义的,而然后从返回语句得到它。

如何解决此问题。

+2

不能从异步函数返回,你必须做的更换** **里面的'onload'处理程序,或者叫里面等超时任何功能是不是正确的修复。 – adeneo

+0

...为什么不使用.setAttribute()而不是正则表达式? – baao

+0

@adeneo你能解释一下如何解决这个问题吗? 顺便说一句我想要在加载时运行此功能 – Pujan

回答

0

使用done()函数可能会帮助您解决此问题。

$.when(ModifyImg).done(function(v){ 
    modifiedHtmlString = htmlString.replace(/<img[^>]+>/g,v); 
    console.log(modifiedHtmlString); 
}); 
+0

尝试过它,仍然是相同的结果它不会更新:( – Pujan