1

我有一个 div 可以更改 id。我已经检查了新的 id 在那里。然后我打电话给新的身份证做别的事情,什么也没发生。

我怎样才能让 div 只有在它具有特定的 css 时才做某事?在示例中,如何仅在 div 为灰色时将其淡出?

$("#red").click(function() {
  $('#red').attr('id', 'grey');
});

$("#grey").click(function() {
  $('#grey').attr('id', 'red');
  $('#grey').fadeOut(800);
});
#red{
	position: absolute;
	top:10px; left:10px;
	width:100px; height:100px;
	background-color:red;
	cursor:pointer;	
}
	
#grey{
	position: absolute;
	top:10px; left:150px; 
	width:100px; height:100px;
	background-color:grey;
	cursor:pointer;	
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="red"></div>

4

2 回答 2

1

由于id动态更改,侦听器停止工作,因为他们无法访问动态更改的元素/属性

所以使用jQuery .on()

代码需要:-

$(document).on('click',"#red",function() {
    $(this).attr('id', 'grey');
});

$(document).on('click',"#grey",function() {
    $(this).attr('id', 'red');
});

工作片段: -

$(document).on('click',"#red",function() {
  //$(this).attr('id', 'grey');
  //better to do same kind of effects
  $(this).fadeOut(800, function() { $(this).attr('id', 'grey').show(); });
});

$(document).on('click',"#grey",function() {
  $(this).fadeOut(800, function() { $(this).attr('id', 'red').show(); });
});
#red{
  position: absolute;
  top:10px; left:10px;
  width:100px; height:100px;
  background-color:red;
  cursor:pointer;	
}
	
#grey{
  position: absolute;
  top:10px; left:150px; 
  width:100px; height:100px;
  background-color:grey;
  cursor:pointer;	
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="red"></div>

于 2018-04-27T11:22:52.243 回答
1

侦听器在页面时间注册。您正在动态更改页面的内容(在这种情况下为属性)。因此,与其监听自身的元素,不如尝试监听文档。

$(document).on("click", "#red", function() {
  $('#red').attr('id', 'grey');
});

$(document).on("click", "#grey", function() {
  var $ele = $(this);
  $ele.fadeOut(800, function() { $ele.attr('id', 'red').css("display", "block") });
});
#red{
  position: absolute;
  top:10px; left:10px;
  width:100px; height:100px;
  background-color:red;
  cursor:pointer;	
}
	
#grey{
  position: absolute;
  top:10px; left:150px; 
  width:100px; height:100px;
  background-color:grey;
  cursor:pointer;	
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="red"></div>

于 2018-04-27T11:24:18.447 回答