检测类

时间:2017-01-30 18:36:33

标签: javascript jquery html arrays

我有数组['.top-menu','txt.name a']

.top-menu =这是div,我想要更改背景颜色;

.name a =这是文字,我想要更改彩色文字;

http://jsfiddle.net/9z5du/1521/

感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

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";});

答案 1 :(得分:1)

您需要在bg范围内将全局each()变量设置为本地:



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>
&#13;
&#13;
&#13;

我认为你也可以只使用CSS

&#13;
&#13;
.top-menu:hover{
  background-color: green;
}
.name a:hover{
  color: green;
}
&#13;
<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>
&#13;
&#13;
&#13;

此外,如果您需要悬停效果,可以使用jQuery&#39; hover()方法:

&#13;
&#13;
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, '');
    }
  );

});
&#13;
<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>
&#13;
&#13;
&#13;