2016-11-12 3 views
-1

Ich versuche, Bilder alt in divWie bekomme ich einzigartige Bilder mit jquery?

das Problem ist, habe ich eine ähnliche Ausgaben Text, vom ersten Bild alt!

Wie können wir es beheben?

var images = $('.box img').attr('alt'); 
$(".box .img-block").text(images).attr("data-title", images); 



<img src="img1.jpg" alt="Text 1"> 
<div class="img-block"></div> 


<img src="img2.jpg" alt="Text 2"> 
<div class="img-block"></div> 

<img src="img3.jpg" alt="Text 3"> 
<div class="img-block"></div> 

Ergebnis

<img src="img1.jpg" alt="Text 1"> 
<div class="img-block">Text 1</div> 

<img src="img2.jpg" alt="Text 2"> 
<div class="img-block">Text 1</div> 

<img src="img3.jpg" alt="Text 3"> 
<div class="img-block">Text 1</div> 

dank

Antwort

0

jQuery(document).ready(function($){ 
 
    $('.box').each(function() { 
 
    $(this).find('.img-block').text($(this).find('img').attr('alt')); 
 
    }); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div class="box"> 
 
<img src="img1.jpg" alt="Text 1"> 
 
<div class="img-block"></div> 
 
</div> 
 

 
<div class="box"> 
 
<img src="img2.jpg" alt="Text 2"> 
 
<div class="img-block"></div> 
 
</div> 
 

 
<div class="box"> 
 
<img src="img3.jpg" alt="Text 3"> 
 
<div class="img-block"></div> 
 
</div> 
 

 
<div class="box"> 
 
<img src="img4.jpg" alt="Text 4"> 
 
<div class="img-block"></div> 
 
</div>

+0

Vielen Dank, es funktioniert gut !, aber dieser Code hat ähnliches Problem, können Sie es bearbeiten bitte? danke 'var imagesalt = $ ('. post. separator a img') .attr ('alt'); $ (". Post. Separator a"). Attr ("Datentitel", imagesalt); $ (". Post. Separator a"). Attr ("daten-lightbox", imagesalt); ' –

+0

Danke Keith –

0
jQuery(document).ready(function($){ 
    $('.box img').each(function() { 
     var alt = $(this).attr('alt'); 
     var box = $(this).closest('.box'); 
     box.find('.img-block').text(alt).attr("data-title", alt); 
    }); 
}); 
0

Sie benötigen besserer Elementumfang Wie wäre es damit:

<div class="box"> 
    <img src="img1.jpg" alt="Image 1 alt" /> 
    <div class="img-block"></div> 
</div> 

<div class="box"> 
    <img src="img2.jpg" alt="Image 2 alt" /> 
    <div class="img-block"></div> 
</div> 

dann kann Ihre js mit jedem Block prperly scoped arbeiten.

Geige here

0

@Keith Vielen Dank, es funktioniert gut !,

aber dieser Code ähnliches Problem hat, können Sie es bearbeiten bitte?

Ich habe versucht, es so wie Sie Ihren Code zu bearbeiten, aber keinen Nutzen

<div class="box"> 
<a href="#"> 
<img src="img1.jpg" alt="Text 1"> 
</a> 
<div class="img-block"></div> 
</div> 

<div class="box"> 
<a href="#"> 
<img src="img1.jpg" alt="Text 2"> 
</a> 
<div class="img-block"></div> 
</div> 

var imagesalt = $('.box a img').attr('alt'); 
$(".box a").attr("data-title", imagesalt); 
$(".box a").attr("data-lightbox", imagesalt); 
Verwandte Themen