问题
I am trying to display user created images on a photos.index view using Laravel 4. As you can see below I am using foreach to go through those pictures. However, as I want to have them displayed in boxes 300px height and 300px width I am using the css background method "cover" in my "box" class.
Now I hav to use JS to change the background image of every box according to what is inserted in the database.
The code below gives me the following result: There are as much boxes displayed as I have in my database. However, they all have the same picture, more exactly the picture that is the last one in the database.
@foreach(array_chunk($photos->getCollection()->all(), 4) as $row)
<div class="row">
@foreach($row as $photo)
<script type="text/javascript">
$(function(){
var boxes =
document.getElementsByClassName("box");
$(boxes).css('background-image',
'url({{ url('img/user_images/images/'. $photo->source_name) }} )');
});
<article class="col-md-3">
<a href="{{ url('photos/'. $photo->id) }}"><div
id="imagecontainer" class="box"></div></a>
</article>
@endforeach
</div>
@endforeach
Now my question is: What do I have to do to change the background image for each box individually?
It could be important to know that those JavaScripts I see if I open the site with Developer Tools DO have the correct link to the picture that should be displayed. However, the CSS background of every div is always the last picture in the DB.
回答1:
The problem is given by the use of the javascript function inside your foreach loop @foreach($row as $photo)
.
@foreach($row as $photo)
<script type="text/javascript">
$(function(){
var boxes =
document.getElementsByClassName("box");
$(boxes).css('background-image',
'url({{ url('img/user_images/images/'. $photo->source_name) }} )');
});
each loop you are rewriting the whole javascript function, and since it does a getElementsByClassName("box"); you are overriding all the boxes div with the last image retrieved by $photos->getCollection()->all()
.
To have a different image for each box individually you should replace the use of the class attribute and use an id, like this:
<div class="row">
@foreach($row as $photo)
<script type="text/javascript">
$(function(){
$("#box-{{$photo->id}}").css('background-image',
'url({{ url('img/user_images/images/'. $photo->source_name) }} )');
});
</script>
<article class="col-md-3">
<a href="{{ url('photos/'. $photo->id) }}"><div
id="box-{{$photo->id}}" class="box"></div></a>
</article>
@endforeach
</div>
回答2:
why don't u just set the background directly on the html?
@foreach($row as $k => $photo)
<article class="col-md-3">
<a href="{{ url('photos/'. $photo->id) }}">
<div style="background-image: {{ url('img/user_images/images/'. $photo->source_name) }}" id="imagecontainer_{{$k}}" class="box"></div>
</a>
</article>
@endforeach
来源:https://stackoverflow.com/questions/21180263/dynamically-change-div-css-background-using-js-within-blade-foreach-loop