Change href value according to child

时间:2015-06-25 18:35:13

标签: javascript jquery

I want to change the href value according to the child background-image value but when I change the background-image value than all href take a same value according to first div.

    <div class="row margin-bottom-20">                          
       <div class="col-md-3 margin-bottom-20">                     
            <a href="" class="over">
                <div class="fill bg-change" style="background-image:url(images/cA4aKEIPQrerBnp1yGHv_IMG_9534-3-2.jpg);"></div>
            </a>
    </div><!-- /.col-md-3 col -->
    <div class="col-md-3 margin-bottom-20">
       <a href="" class="over">
          <div class="fill bg-change" style="background-image:url(images/J3URHssSQyqifuJVcgKu_Wald.jpg);"></div>
       </a>
    </div><!-- /.col-md-3 col -->
    <div class="col-md-3 margin-bottom-20">
       <a href="" class="over">
          <div class="fill bg-change" style="background-image:url(images/cA4aKEIPQrerBnp1yGHv_IMG_9534-3-2.jpg);"></div>
       </a>
    </div><!-- /.col-md-3 col -->
    <div class="col-md-3 margin-bottom-20">
       <a href="" class="over">
           <div class="fill bg-change" style="background-image:url(images/J3URHssSQyqifuJVcgKu_Wald.jpg);"></div>
       </a>
    </div><!-- /.col-md-3 col -->
    </div><!-- /.row -->
<script type="text/javascript">
  $('.over').attr('href',function(e){
     var bg_img = $('.fill').css("background-image");
     bg_img = bg_img.replace(/.*\s?url\([\'\"]?/, '').replace(/[\'\"]?\).*/, '');
     return bg_img;
});
</script>

1 个答案:

答案 0 :(得分:0)

I'd suggest: $('.over').prop('href', function () { return $(this).find('.fill').css('background-image').replace(/.*\s?url\([\'\"]?/, '').replace(/[\'\"]?\).*/, ''); }); This iterates over each of the .over elements, and updates the href property to the processed string found in the background-image property. It's worth noting that I haven't verified the results of the regular expression, and simply copied that part from your own posted code (given that it seems to work, or isn't mentioned in your question as not working). References: JavaScript: String.prototype.replace(). jQuery: prop().