jquery - 如何在 jQuery 中调用动态选择器?

标签 jquery css

我有一个div,我改变了id。我已经检查过新的 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>

最佳答案

由于 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>

关于jquery - 如何在 jQuery 中调用动态选择器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50061296/

相关文章:

javascript - 通过 Javascript 控制台点击元素

javascript - 在 DOM 中存储数据 - 自定义属性或 .data()

css - 导航栏中的 Bootstrap 3.0 按钮

html - 悬停时更改属性

html - 为什么 HTML 实体会忽略我在 Outlook 2003 和 IE7 中的跨度代码

jquery - appendTo/prependTo 但我不想添加内容而是想替换内容。 html到?

jquery - 如果服务器返回缓存预防 header ,是否需要禁用 jQuery 缓存技巧?

JQuery Mobile <LI> 文本长度

javascript - 显示元素一秒钟,然后隐藏它

CSS - 将鼠标悬停在 li 元素(下拉菜单)上时执行转换