j在 for 循环中查询多个变量
jQuery multiple variables in for loops
这可能是一件简单的事情,但就是想不通。
假设我有五十个类似的函数,其中有两个:
var unit = ['red', 'pink']
var unit2 = ['red2', 'red2']
$('#red').click(function() {
if($('#red2').is(':hidden')) {
$('#red2').toggle();
} else {
$('#red2').toggle();}}}
和
$('#pink').click(function() {
if($('#pink2').is(':hidden')) {
$('#pink2').toggle();
} else {
$('#pink').toggle();}}}
我想在一个/两个 for 循环中添加所有这些函数。我试过这个:
for (var i = 0; i < unit.length; i++) {
for (var y = 0; y < unit2.length; y++) {
$('#i').click(function() {
if($('#y').is(':hidden')) {
$('#y').toggle();
} else {
$('#y').toggle();}}}}
.toggle()
方法检测元素本身的可见性,无需使用if
语句,您可以使用this
关键字来引用单击的元素:
$('#red, #pink').on('click', function() {
// Based on the id property of the clicked element
// this selects #red2 or #pink2 element
$('#' + this.id + '2').toggle();
});
另请注意,$('#i')
选择ID 为 i
的元素,则应连接字符串:
$('#' + i).foo();
你应该连接字符串:
for (var i = 0; i < unit.length; i++) {
$('#' + unit[i])
.attr('data-dst', unit2[i])
.click(function() {
var dst = $(this).attr('data-dst');
$('#' + dst).toogle();
}
}
相关文章:
- 查询后websql成功回调无法访问变量
- 使用MEAN堆栈-查询MongoDB并将值作为变量传递
- Mongoose从查询中设置本地变量
- 我想将查询字符串变量添加到JSON名称/值对中
- 如何使用EnquireJS使AngularJS范围变量依赖于媒体查询
- 如何在 Meteor 中的 Mongo 查询中使用变量作为字段名称
- 通过 AJAX 调用 PHP 文件,将 $_GET 变量传递到 MySQL 查询中,然后回显到响应中
- 获取重复Get变量的查询字符串值
- 从查询字符串中获取变量,将其与Javascript中的数组匹配
- 如何设置查询字符串中的变量
- 如何在mongoose/node.js中的聚合查询中使用变量
- JQuery的PHP查询数组变量
- 如何在nodejs中的MySQL查询中使用多个变量
- 表示 js 总变量查询
- 节点.js中的变量查询
- 在mysql中使用javascript变量查询并填充listview
- 使用jquery变量查询json对象
- 如何在mysql中挑选变量.查询回调函数
- 了解JavaScript变量查询
- Mongodb / javascript变量查询