使用 jquery/javascript 设置多个 img alt 侦听器
Setting multiple img alt listeners with jquery/javascript
我有一个循环遍历一组键,根据它们的值创建事件侦听器。
for (var keys in key) {
if (excludeList.indexOf(keys) == -1) {
d3.selectAll('img[alt="' + keys + '"]').on('click, function() {
console.log(keys);
d3.selectAll('img[alt="' + keys +'"').style('opacity','0.5')
})
}
}
每个侦听器都会覆盖前一个,因此最后一个键是唯一剩下的侦听器。
如何在不同的 alt 标签上设置监听器?
您不是在寻找 array/object 值,而是在寻找索引(keys
与 key[keys]
,或者语义正确:key
与 keys[key]
).
这是一个固定的例子:
var keys = {
a: 'shomz' // 'In code veritas' not listed so no event
,b: 'another'
}
var excludeList = ['excluded'];
for (var key in keys) {
if (excludeList.indexOf(keys[key]) == -1) {
attach(keys[key]);
}
}
function attach(k) {
$('img[alt="' + k + '"]').click(function() {
console.log(k);
$('img[alt="' + k + '"').css('opacity', '0.5')
})
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img alt="In code veritas" />
<img alt="shomz" />
<img alt="another" />
<img alt="excluded" />
我有一个循环遍历一组键,根据它们的值创建事件侦听器。
for (var keys in key) {
if (excludeList.indexOf(keys) == -1) {
d3.selectAll('img[alt="' + keys + '"]').on('click, function() {
console.log(keys);
d3.selectAll('img[alt="' + keys +'"').style('opacity','0.5')
})
}
}
每个侦听器都会覆盖前一个,因此最后一个键是唯一剩下的侦听器。
如何在不同的 alt 标签上设置监听器?
您不是在寻找 array/object 值,而是在寻找索引(keys
与 key[keys]
,或者语义正确:key
与 keys[key]
).
这是一个固定的例子:
var keys = {
a: 'shomz' // 'In code veritas' not listed so no event
,b: 'another'
}
var excludeList = ['excluded'];
for (var key in keys) {
if (excludeList.indexOf(keys[key]) == -1) {
attach(keys[key]);
}
}
function attach(k) {
$('img[alt="' + k + '"]').click(function() {
console.log(k);
$('img[alt="' + k + '"').css('opacity', '0.5')
})
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img alt="In code veritas" />
<img alt="shomz" />
<img alt="another" />
<img alt="excluded" />