【问题标题】:Detect div or txt array in class检测类中的 div 或 txt 数组
【发布时间】:2017-01-31 02:49:21
【问题描述】:
【问题讨论】:
-
请花时间阅读How to Ask。问题应该是自包含的并包含相关代码。演示很棒,但只能用于支持问题中实际存在的内容。我们不需要离开现场来查看您的问题是什么
标签:
javascript
jquery
html
arrays
【解决方案1】:
您需要在each() 范围内将全局bg 变量设置为本地:
var ids = ['.top-menu', 'txt.name a'];
var clbg = '';
$.each(ids, function(index, value) {
var bg;
if (value.indexOf('txt') > -1) {
value = value.replace("txt", "");
bg = 'color';
} else {
bg = 'background-color';
}
$(value)
.mouseover(function(event) {
event.stopPropagation();
$(value).css(bg, 'green');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="top-menu">This is div, we will change background-color</div>
<div class="name">
<a href="#">This is text, we will change color</a>
</div>
我想你也可以只使用CSS:
.top-menu:hover{
background-color: green;
}
.name a:hover{
color: green;
}
<div class="top-menu">This is div, we will change background-color</div>
<div class="name">
<a href="#">This is text, we will change color</a>
</div>
另外,如果你需要悬停效果,你可以使用jQuery的hover()方法:
var ids = ['.top-menu', 'txt.name a'];
var clbg = '';
$.each(ids, function(index, value) {
var bg;
if (value.indexOf('txt') > -1) {
value = value.replace("txt", "");
bg = 'color';
} else {
bg = 'background-color';
}
$(value).hover(
function(event) {
event.stopPropagation();
$(value).css(bg, 'green');
}, function() {
$(value).css(bg, '');
}
);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="top-menu">This is div, we will change background-color</div>
<div class="name">
<a href="#">This is text, we will change color</a>
</div>
【解决方案2】:
bg 是全局的。所以它将具有最后一次迭代的 elems 值的值。您需要将其设置为函数的本地:
var ids = ['.top-menu','txt.name a'];
var clbg = '';
$.each(ids, function(index, value) {
if (value.indexOf('txt') > -1)
{
value = value.replace("txt", "");
var bg = 'color';//var to make it local
}
else
{
var bg = 'background-color';//if bg is global, it will be background-color for all elems, you need var to make it local
}
$(value).mouseover(function(event) {
event.stopPropagation();
$(value).css(bg,'green');
});
});
http://jsfiddle.net/ekddev4h/
顺便说一句,要短得多:
[[".top-menu","color"],["txt.name a","background-color"].map(el=>document.querySelector(el[0])).forEach(el=>el[0].onmouseover=function(){this.style[el[1]="green";});