Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
223 views
in Technique[技术] by (71.8m points)

javascript - I can't get the OR operator to work properly

For some reason I do not understand, the OR operator does not work properly.

In below example I am trying to create a hover effect with jquery, which is only applied if the id of the hovered element is not equal to "f1" or "c1"

But as can be seen in the provided example it does not work. Any ideas?

$(document).on("mouseenter", ".123456", function() {
  if (this.id != 'f1' || this.id != 'c1') {
    $(this).css("background-color", "green")
    $(this).find('span').css("color", "red")
  }
});
$(document).on("mouseleave", ".123456", function() {
  if ((this.id != 'f1') || (this.id != 'c1')) {
    $(this).css("background-color", "white")
    $(this).find('span').css("color", "black")
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="a1" class="123456">
  <span>a1</span>
</div>

<div id="f1" class="123456">
  <span>f1</span>
</div>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Change the or's to and's.

$(document).on("mouseenter", ".123456", function() {
  if (this.id != 'f1' && this.id != 'c1') {
    $(this).css("background-color", "green")
    $(this).find('span').css("color", "red")
  }
});
$(document).on("mouseleave", ".123456", function() {
  if ((this.id != 'f1') && (this.id != 'c1')) {
    $(this).css("background-color", "white")
    $(this).find('span').css("color", "black")
  }
});

This way, the hover effect will only be applied to elements whose id is not c1 AND to elements whose id is not f1.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...