简体   繁体   中英

Selecting image using $('img[src$=“image source end string in variable”]') getting undefined value

I have this code wherein there's an image in id #imgfullview and images on class imglist .

I want to get the image src of #imgfullview and get the matching image on class imglist base on src attribute.

I used this selector https://api.jquery.com/attribute-ends-with-selector

This is working if i just used selector using string

var x = $(".imglist[src$='b-640x624.jpg']");
var imglistmatched = x.attr("src");
alert(imglistmatched );

But if I used a selector changing the string to variable, I'm getting undefined value not sure why though I have exact string as 'b-640x624.jpg' on variable splitimgurl from string split function based on full patch src or through assigning the exact string if I check it on console.log or alert the variable

var currentimg =$("#imgfullview").attr("src");
var splitimgpath = currentimg.split('_');
var splitimgurl = splitimgpath[2]; //or this splitimgurl = "b-640x624.jpg";
var x = $(".imglist[src$=splitimgurl]");
var imglistmatched = x.attr("src");
alert (imglistmatched);

I tried this

var x = $(".imglist[src$="splitimgurl"]");

and this

var x = $(".imglist[src$="+splitimgurl+"]");

and this

var x = $(".imglist[src$=""+splitimgurl]");

it does not work

Please see this on fiddle http://jsfiddle.net/w7n3sh2v/

I found the related question below but it does not help

jQuery $("img[src=the_image_souce]").attr('src','new_src'); does not work

May I know if there's a correct way to put variable on Attribute Equals Selector?

You missed '' in the

var x = $(".imglist[src$=" + splitimgurl + "]");

Try this

var x = $(".imglist[src$='" + splitimgurl + "']");

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM