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

标签 jquery variables jquery-selectors

我正在尝试查找具有与变量匹配的“src”的图像。我已使用“alert”来确保变量“currentThumbnail”正确,因此我认为问题在于语法。这就是我现在所拥有的:

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

问题出在“img[src=currentThumbnail]”。我需要更改什么才能使其有效?

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

最佳答案

var nextT = $('.thumbnails a img[src=currentThumbnail]');

应该是

var nextT = $('.thumbnails a img[src="'+ currentThumbnail +'"]');

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

@ThiefMaster 的重要评论

The attribute values in selectors should be quoted. The docs says it's a requirement and I think the only reason why it's not enforced is backwards compatibility

关于jquery - 如何在 jQuery 选择器中使用变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10962115/

相关文章:

javascript - 下拉菜单上的多个属性选择器?

javascript - jquery 检查选​​项是否被选中

java - jsp中显示有限行数

jquery - 使用可排序如何禁止特定类别的项目移动到特定列表

javascript - Highcharts 每小时刻度间隔

python - 如何在 Python 中创建不可变列表?

javascript - 如何将 csrf_token 传递给 django 中的 javascript 文件?

javascript - PHP/MySQL的返回如何返回到调用页面?

shell 脚本 : Define a variable within an if-statement

javascript - 检索并修改 :before element with jQuery