i have this scenario:
<img class="prev" data-modal-img-src="asd"/>
<span></span>
<img class="next"/>
now on cllick i want to get the .prev img element src attr, and i do:
$(function(){
$('span').bind('click',function(){
var _img_src = $(this).prev('img').attr('data-modal-img-src');
alert(_img_src);
});
});
it doesn't works as expected, any suggestion?
PS: do not use -1 like is rayining -1
To get the prev they should have common parent could by body
tag or div
etc. and you do not have attribute 'data-modal-img-src'
. You should use on
instead of bind as bind is deprecated . Also use data()
instead of attr()
for data attributes.
prev() , Get the immediately preceding sibling of each element in the set of matched elements, optionally filtered by a selector, jQuery documents .
<img class="prev" data-modal-img-src = "123"/>
<span></span>
<img class="next"/>
$(function () {
$('span').bind('click', function () {
var _img_src = $(this).prev('img').data('modal-img-src');
alert(_img_src);
});
});
Using data()
$(function () {
$('span').bind('click', function () {
var _img_src = $(this).prev('img').data('modal-img-src');
alert(_img_src);
});
});
使用data()
而不是attr()
$(this).prev('img').data('modal-img-src')
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.