我有几个 div 标签,希望能够使用 jquery 创建另一个标签(单击 #four),然后将其淡入,然后在另一次单击时淡出。
<body>
<div id="one">one</div>
<div id="two">two</div>
<div id="four">four</div>
</body>
但是我的代码立即淡出# Five,尽管我尝试在所有地方为 fadeOut 选择 .on('click'),但与 fadeIn ('#four') 的区域相同
$(document).ready(function() {
$("#four").on('click',function() {
var newbox = $('<div id="five">five</div>');
$(newbox).hide().insertAfter("#four").fadeIn('slow');
});
})
$(document).ready(function() {
$('body:not(#four)').on('click', function() {
$("#five").fadeOut('slow');
});
});
知道我哪里错了吗?谢谢,菲利普
最佳答案
//$("#four").on('click',function() { //the user can creat as many div as he wants
$("#four").one('click',function() { //the user fire this event only once
var newbox = $('<div id="five">five</div>');
newbox.on('click', function(){
$(this).fadeOut();
});
newbox.hide().insertAfter("#four").fadeIn('slow');
});
})
如果您声明newbox
如$("<tags>")
您不需要再次使用$(newbox)
因为您已经选择了它。
其他解决方案是 delegate
event
$(document).on('click', function(e){
if($(e.target).attr('id') === 'four') return false;
$("#five").fadeOut();
});
关于jquery 立即淡出,而不是 .on ('click' ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17751023/