在jQuery选择器中添加变量?
问题描述:
林试图通过它的标题,它存储在一个变量来选择一个元素:在jQuery选择器中添加变量?
$('.images').hover(function(){
var img = $(this).attr("title");
$(".image-border[title='img']").addClass('show');
}
但是,你可以想像,该变量被视为字符串的一部分......这是甚至有可能?
答
你可能会得到答案告诉你使用字符串连接,如:
不要做这种方式$('.images').hover(function() {
var img = $(this).attr('title');
$('.image-border[title="' + img + '"]').addClass('show');
});
这是一个坏主意。您尚未转义存储在img
中的值,并且可能会破坏选择器。
的权的方式做这样的检查是选择一切可以静态,然后filter
结果只包括匹配的动态值的那些:
$('.images').hover(function() {
var img = $(this).attr('title');
$('.image-border[title]').filter(function() {
return $(this).attr('title') === img;
}).addClass('show');
});
这是更多的我正在寻找的方法。即使是最微小的事情,安全也很重要! - 谢谢 –
好的,现在看起来好多了。 –
使用此选择器运行过滤器函数'.image-border [title]'。这并不是说它改变了@zzzzBov的精确解答。它只是减少了要测试的元素的数量,因为它只提供了在其中具有title属性的.image-border元素。 – SuperNOVA