目标同一类不同的id

时间:2017-12-14 19:28:12

标签: javascript jquery

似乎在定位子元素时出现了错误,似乎无法悬停。

$(document).ready(function() {

  $('.requested_user').on('mouseenter', function() {
    var currentIdMouse = $(this).attr('id');
    $('#' + currentIdMouse + ' .requested_user').css("text-decoration", "underline");
    $('#' + currentIdMouse + ' .requested_user').css("color", "blue");
    $('#' + currentIdMouse + ' .popup_window').show();
  });
  $('.requested_user').on('mouseleave', function() {
    var currentIdMouse = $(this).attr('id');
    $('#' + currentIdMouse + ' .requested_user').css("text-decoration", "none");
    $('#' + currentIdMouse + ' .requested_user').css("color", "white");
    $('#' + currentIdMouse + ' .popup_window').hide();
  });

});
.requested_user {
  width: 100px;
  height: 20px;
}

.requested_user:hover {
  cursor: pointer;
}

.popup_window {
  position: relative;
  left: 20px;
  top: -10px;
  width: 100px;
  height: 100px;
  background-color: green;
  opacity: 0.6;
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div class="requested_user" id="item1">
  item1 content
  <div class="popup_window" id="item1">item1 popup content</div>
</div>

<div class="requested_user" id="item2">
  item2 content
  <div class="popup_window" id="item2">item2 popup content</div>
</div>

小提琴:https://jsfiddle.net/xht48eLg/

2 个答案:

答案 0 :(得分:1)

如此接近,只需更改.live的{​​{1}}即可:

.on 变为$('.requested_user').live('mouseenter', function() {

$('.requested_user').on('mouseenter', function() { 变为$('.requested_user').live('mouseleave', function() {

查看小提琴的更新版本:https://jsfiddle.net/MarcDBosse91/xht48eLg/1/

另外,正如@Peter Darmis的评论所述:

  

从jQuery 1.7开始,不推荐使用.live()方法。使用.on()来   附加事件处理程序。旧版jQuery的用户应该使用   .delegate()优先于.live()api.jquery.com/live

答案 1 :(得分:0)

根本不需要id查找。 this是处理程序中的requested_user,popup_window是其中的子项。

$(document).ready(function() {
  $('.requested_user').on('mouseenter', function() {
    this.style.textDecoration = 'underline';
    this.style.color = 'blue';
    $('.popup_window', this).show();
  });
  $('.requested_user').on('mouseleave', function() {
    this.style.textDecoration = 'none';
    this.style.color = 'white';
    $('.popup_window', this).hide();
  });
});
.requested_user {
  width: 100px;
  height: 20px;
}

.requested_user:hover {
  cursor: pointer;
}

.popup_window {
  position: relative;
  left: 20px;
  top: -10px;
  width: 100px;
  height: 100px;
  background-color: green;
  opacity: 0.6;
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div class="requested_user" id="item1">
  item1 content
  <div class="popup_window">item1 popup content</div>
</div>

<div class="requested_user" id="item2">
  item2 content
  <div class="popup_window">item2 popup content</div>
</div>