我找不到问题。当我关闭红色图层并再次单击第一个按钮时,为什么此代码会生成“X”按钮的多个副本?
我认为init
就像一个只运行一次的正确构造函数,对吗?
这是一个说明问题的jsfiddle:
http://jsfiddle.net/yoniGeek/mWghr/
谢谢你的时间!
Y /
html:
<div class="Main">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Phasellus non nisl mauris. Phasellus eget viverra mi.
Curabitur elementum tristique nibh, et faucibus eros
fermentum ut. Pellentesque non nisi augue.
Nulla facilisis ultrices malesuada. Sed bibendum lacus
sed lorem auctor rutrum.
iam semper justo id diam
</p>
<p id="last_child" > Lorem ipsum dolor
sit amet, consectetur adipiscing elit.
Phasellus non nisl mauris. Phasellus eget viverra mi.
Curabitut interdum velit ultricies.
</p>
<div id="layer_on" ></div>
</div>
jquery-code:
(function(){
$('html').addClass('js');
//var red_layer;
var red_layer = {
red_box: $('#layer_on'),
init: function() {
$('<button></button>', {
text: 'push me'
}).insertAfter('.Main #last_child').on('click', this.show);
},
show: function() {
red_layer.close.call(red_layer.red_box);
red_layer.red_box.show();
},
close: function() {
var $this = $(this);
$('<span class="close">X</span>').prependTo(this).on('click', function() {
$this.hide();
});
}
//anonymous function
}; // red_layer object ends
red_layer.init(); //We call it back (the function )
})();
答案 0 :(得分:1)
答案 1 :(得分:0)
为什么不在init
方法中添加关闭按钮?您只需要添加一次按钮。实际上,每次显示框时都会添加X
按钮。每次点击push me
时,都会拨打show()
,然后拨打.close()
,其前面会有另一个X
。相反,请从init
函数调用close:
var red_layer = {
red_box: $('#layer_on'),
init: function() {
// Console.log(this);
$('<button></button>', {
text: 'push me'
}).insertAfter('.Main #last_child')
.on('click', this.show);
red_layer.close.call(red_layer.red_box); // <--- HERE
},
show: function() {
// NOT HERE
red_layer.red_box.show();
},
我认为你的close
方法不一定是一种方法。它只是添加X
按钮,这似乎是一次性的事情。它的作用也不明显。似乎调用close
实际上会关闭该框,但在这种情况下它不会。
答案 2 :(得分:0)
由于您在关闭函数中多次附加span标记,因此您会看到多个'x'。我重写了你的近距离函数,它完美无缺。
close: function() {
var that = $(this);
that.html('<span class="close">X</span>');
that.on('click', function() {
that.hide();
});
}