如何在jQuery选择器中使用变量?

4 variables jquery jquery-selectors

我正在尝试找到一个带有与变量匹配的'src'的图像.我使用'alert'来确保变量'currentThumbnail'是正确的,所以我认为问题在于语法.这就是我现在所拥有的:

var currentImage = $('.imageMain').attr('src');
var currentThumbnail = currentImage.substring(6);
var nextT = $('.thumbnails a img[src=currentThumbnail]');
Run Code Online (Sandbox Code Playgroud)

问题在于'img [src = currentThumbnail]'.我需要更改什么才能使其有效?

如果不清楚,我很乐意添加更多信息.谢谢!

the*_*dox 7

var nextT = $('.thumbnails a img[src=currentThumbnail]');
Run Code Online (Sandbox Code Playgroud)

应该

var nextT = $('.thumbnails a img[src="'+ currentThumbnail +'"]');
Run Code Online (Sandbox Code Playgroud)

您需要字符串连接,因为您在currentThumbnail字符串中使用变量.

来自@ThiefMaster的重要文章

应引用选择器中的属性值.文档说这是一个要求,我认为没有强制执行的唯一原因是向后兼容性