.Css()函数返回undefined

时间:2017-05-18 12:19:39

标签: javascript jquery html angularjs css3

目前我在我的代码片段中遇到一个问题,我正在根据图像代码从css文件中检索图像网址,其中图像代码来自其他网站     并且另一个函数将图像代码作为参数使其成为css类。

基于css类在jquery中使用.css()来检索图像url,但是当页面最初加载时,它返回“undefined”几秒后返回正确的图像URL:

JS函数将图像代码设为css类:

$scope.placeholderNetworkImage = function(networkBenefitIcon){
    var selectorClassName = "."+ networkBenefitIcon;
    var blnResult = false;

     if(networkBenefitIcon!=="null" && networkBenefitIcon!=="")
     {

        var imagePresent = $(selectorClassName).css('backgroundImage');
        console.log("image of url is: "+imagePresent);
        if (imagePresent == 'none' || imagePresent == null) {
           blnResult = true;
        }
        else 
        {
            blnResult = false;
        }
     }
    else
    {
       blnResult = true;
    }
       return blnResult;
}

HTML代码

<div class="media-left">
  <ul>
    <li class="networkBenefitIconLi" ng-repeat="networkBenefitIcon in 
           item.t_css_tariffBenefit.split('|') track by $index | limitTo:3">
      <span ng-class="networkBenefitIcon" class="networkBenefitIcon" ng-
                   show="!placeholderNetworkImage(networkBenefitIcon)">
          </span>
      <span class="networkBenefitIcon tickLightGray" ng-
                    show="placeholderNetworkImage(networkBenefitIcon)">
          </span>
    </li>
  </ul>
</div> 

输出:

it was output shown on console here you can find some were image url's and some are showing "undefined"

请帮助我解决这个问题,因为这是我们方面的一个巨大的性能问题。请任何人告诉我为什么它返回“未定义”,即使图像存在于CSS中。

1 个答案:

答案 0 :(得分:-1)

我想你已经有了答案。首先,等到DOM准备好了! 然后,获取背景图片URL(编辑答案并留下一个片段以显示证据):

&#13;
&#13;
$(document).ready(function () {

  function getImageBackgroundUrl ($el) {
    var imgUrl = $el.css('backgroundImage')
    return imgUrl
  }

  function doSomething (imgUrl) {
    console.log('imgUrl is', imgUrl)
  }

  var images = $('.my-images ul li');
  $.each(images, function (k, v) {
      var $el = $(v)
      var imgUrl = getImageBackgroundUrl($el)      
      doSomething(imgUrl)
  })
})
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<style>
.a {
  background-image: url(https://unsplash.it/200/305?2)
}
.b {
  background-image: url(https://unsplash.it/200/305?3)
}
.c {
  background-image: url(https://unsplash.it/200/305?4)
}
</style>
<div class="my-images">
  <ul>
    <li class="a"></li>
    <li class="b"></li>
    <li class="c"></li>
  </ul>
</div>
&#13;
&#13;
&#13;