JQuery - 按数据属性查找元素 = 变量
JQuery - finding element(s) by data attribute = variable
使用(自定义)JQuery data-attributes
检索显示这些图标的元素,我正在使用以下工作代码成功更改图标:
<i class="glyphicon glyphicon-check" data-year="2014" data-flag_check="1"></i>
...
<script>
...
$('i[data-year="2014"]').removeClass('glyphicon-check').addClass('glyphicon-unchecked');
但是,如果我尝试用变量替换常量 2014
,我的代码将停止工作。
var yearIn = "2014";
$('i[data-year=yearIn]').removeClass('glyphicon-check').addClass('glyphicon-unchecked');
问题:
是否可以使用变量执行此操作?
可能的跟进问题:
如果是这样,谁能检测出我的语法有什么问题?
您只是缺少字符串连接:
var yearIn = "2014";
$('i[data-year=' + yearIn + ']').removeClass('glyphicon-check').addClass('glyphicon-unchecked');
// ------------^^^^^^^^^^^^^^
或者在 ES2015+ 中,您可以使用带有替换标记的模板文字:
var yearIn = "2014";
$(`i[data-year=${yearIn}]`).removeClass('glyphicon-check').addClass('glyphicon-unchecked');
// ^------------^^^^^^^^^-^
FWIW,当它来自变量时,我总是在选择器中的值周围使用引号,以防万一变量以空格等结尾:
var yearIn = "2014";
$('i[data-year="' + yearIn + '"]').removeClass('glyphicon-check').addClass('glyphicon-unchecked');
// ------------^--------------^
或
var yearIn = "2014";
$(`i[data-year="${yearIn}"]`).removeClass('glyphicon-check').addClass('glyphicon-unchecked');
// ------------^---------^
您使用的是字符串文字 'yearIn'
而不是变量 yearIn
,执行类似这样的操作来连接字符串:
$('i[data-year=' + yearIn + ']').removeClass('glyphicon-check').addClass('glyphicon-unchecked');
使用(自定义)JQuery data-attributes
检索显示这些图标的元素,我正在使用以下工作代码成功更改图标:
<i class="glyphicon glyphicon-check" data-year="2014" data-flag_check="1"></i>
...
<script>
...
$('i[data-year="2014"]').removeClass('glyphicon-check').addClass('glyphicon-unchecked');
但是,如果我尝试用变量替换常量 2014
,我的代码将停止工作。
var yearIn = "2014";
$('i[data-year=yearIn]').removeClass('glyphicon-check').addClass('glyphicon-unchecked');
问题: 是否可以使用变量执行此操作?
可能的跟进问题: 如果是这样,谁能检测出我的语法有什么问题?
您只是缺少字符串连接:
var yearIn = "2014";
$('i[data-year=' + yearIn + ']').removeClass('glyphicon-check').addClass('glyphicon-unchecked');
// ------------^^^^^^^^^^^^^^
或者在 ES2015+ 中,您可以使用带有替换标记的模板文字:
var yearIn = "2014";
$(`i[data-year=${yearIn}]`).removeClass('glyphicon-check').addClass('glyphicon-unchecked');
// ^------------^^^^^^^^^-^
FWIW,当它来自变量时,我总是在选择器中的值周围使用引号,以防万一变量以空格等结尾:
var yearIn = "2014";
$('i[data-year="' + yearIn + '"]').removeClass('glyphicon-check').addClass('glyphicon-unchecked');
// ------------^--------------^
或
var yearIn = "2014";
$(`i[data-year="${yearIn}"]`).removeClass('glyphicon-check').addClass('glyphicon-unchecked');
// ------------^---------^
您使用的是字符串文字 'yearIn'
而不是变量 yearIn
,执行类似这样的操作来连接字符串:
$('i[data-year=' + yearIn + ']').removeClass('glyphicon-check').addClass('glyphicon-unchecked');