我有一个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/