binding back after die using live?
I didn't mean it to rhyme!
But I need help. I have done some live function events with jquery, mouseenter, mouseleave, and click. If mouseenter an element, another element shows, and if mouseleaves, that element disappears. If clicked,开发者_JAVA技巧 the element is still shown, and mouseleaves dies.
Now, my question is, how do you rebind how make that element disappear when you click again.
$('.block').live("mouseenter",function(){
var id= $(this).attr('id');
$('#arrowPreview'+id).show();
}).live("mouseleave",function(){
var id= $(this).attr('id');
$('#arrowPreview'+id).hide();
}).live("click",function(){
var id= $(this).attr('id');
$('#arrowPreview'+id).show();
$('.block').die("mouseleave");
});
Thats my script so far. Thanks!
You could keep the mouseleave
handler on the clicked element, and instead change a piece of state information attached to the element when it is clicked so you know that the mouseleave
event should perform no action.
var blocks = $('.block');
blocks.live("mouseenter",function(){
var id = $(this).attr('id');
$('#arrowPreview'+id).show();
}).live("mouseleave",function(){
var obj = $(this);
if (!obj.data('inactive')) {
var id = obj.attr('id');
$('#arrowPreview'+id).hide();
}
}).live("click",function(){
var obj = $(this);
var id = obj.attr('id');
$('#arrowPreview'+id).show();
obj.data('inactive', !obj.data('inactive'));
});
Live demo: http://jsfiddle.net/D9zaK/5/
One way would be not to call die()
in the first place. Instead, you can store the "clicked" state in the document's data and only hide the element in your mouseleave
handler if the "clicked" state allows it.
EDIT: From the requirements in your latest comment, it looks like you want the "clicked" state to be maintained for each element instead of globally (which means die()
wasn't the way to go in the first place, because it unbinds the handler globally).
The following code hopefully fulfills your requirements:
$(".block").live("mouseenter", function() {
var $arrow = $("#arrowPreview" + this.id);
if (!$arrow.data("freeze")) {
$arrow.show();
}
}).live("mouseleave", function() {
var $arrow = $("#arrowPreview" + this.id);
if (!$arrow.data("freeze")) {
$arrow.hide();
}
}).live("click", function() {
var $arrow = $("#arrowPreview" + this.id);
$arrow.data("freeze", !$arrow.data("freeze"));
});
I personally wouldn't use die. The easy way to do it is to just set a flag. Once click is registered, flag is true. mouseleave function has a conditional to check if flag is set, and will not hide if the flag is true. Next time you click, unset the flag and either hide it right away or let mouseleave do its thing.
精彩评论