Here is the code I have. This can not be changed, I have to work with the structure as is.
<div class="container">
<div class="contain_box">
<a href="something">
<img class="my_img" src="some_image">
</a>
<div class="variants">
<div class="var" rel="123" data="321"></div>
<div class="var" rel="1234" data="4321"></div>
</div>
</div>
<div class="contain_box">
<a href="something">
<img class="my_img" src="some_image">
</a>
<div class="variants">
<div class="var" rel="456" data="654"></div>
<div class="var" rel="4567" data="7654"></div>
</div>
</div>
<div class="contain_box">
<a href="something">
<img class="my_img" src="some_image">
</a>
<div class="variants">
<div class="var" rel="789" data="987"></div>
<div class="var" rel="7890" data="0987"></div>
</div>
</div>
</div>
What I need is when I click on one of the images it will pull the rel and the data from its first variant, add those attributes to the image tag. Right now I am trying this and I only get the undefined. I am using the undefined to clear out those variables from the current values.
$(document).on("click", '.my_img', function(e){
e.preventDefault();
data = undefined;
rel = undefined;
var new_rel = $('.var').attr('rel');
var new_data = $('.var').attr('data');
$('.my_img').attr('rel', new_rel);
$('.my_img').attr('data', new_data);
data = $(this).attr('variant');
rel = $(this).attr('rel');
}
Any insights or help would be awesome! Thanks in advance!
Find the parent container ( .contain_box
) relative to the clicked image, then the first variant from there:
$(document).on("click", '.my_img', function(e){
e.preventDefault();
var firstVariant = $(this).closest('.contain_box').find('.var').first();
data = firstVariant.attr('rel');
rel = firstVariant.attr('data');
$(this).attr({
data : data,
rel : rel
});
console.log(data);
console.log(rel);
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.