在 jQuery 选择器中添加变量?
adding variable in jQuery selector?
我正在尝试 select 通过标题存储在变量中的元素:
$('.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
中的值,它可能会破坏 selector.
进行这种检查的正确方法是select静态地检查所有内容,然后filter
结果只包括那些匹配动态值:
这样做
$('.images').hover(function () {
var img = $(this).attr('title');
$('.image-border[title]').filter(function () {
return $(this).attr('title') === img;
}).addClass('show');
});
我正在尝试 select 通过标题存储在变量中的元素:
$('.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
中的值,它可能会破坏 selector.
进行这种检查的正确方法是select静态地检查所有内容,然后filter
结果只包括那些匹配动态值:
$('.images').hover(function () {
var img = $(this).attr('title');
$('.image-border[title]').filter(function () {
return $(this).attr('title') === img;
}).addClass('show');
});