Jquery show/hide
I've got the following code:
$('#hideButton').click(function() {
$('#menu').animate({
opacity: 0.25
});
$('#hideButton').val('Show');
$('#hideButton').attr('id','showButton');
});
$('#showButton').click(function() {
$('#menu').animate({
opacity: 1
});
$('#showButton').val('Hide');
$('#showButton').attr('id','hideButton');
});
As you see #hideButton
should reduce div opacity to 0.25 and then change it's id to showButton. When I click showButton it should increase the div opacity to 1 but for som开发者_如何学运维e reason the code isn't working after clicking the changed button.
I would not modify the IDs and would just go off of the value of the button to determine which action should be taken:
$('#hideButton').click(function() {
var ele = $(this);
if(ele.val() == "Hide"){
ele.val('Show');
$('#menu').animate({ opacity: 0.25 });
}else{
ele.val('Hide');
$('#menu').animate({ opacity: 1 });
}
});
Working example: http://jsfiddle.net/Rt4QY/
The events are bound to the elements when they are loaded. When they are loaded, there is no element with the id showbutton, so that doesn't get attached to anything. Instead, you should put an if statement in your hide function to check the val() of the button. If it is "hide" do your hide functionality, if it is "show" do the show.
Don't change your button's ID. Rather work with CSS classes.
The problem you're having you're setting a click handler to a button with ID showButton
, that doesn't exists at the moment when you're binding click event to it. Your button will become available after you've clicked your hideButton
because that will convert it to showButton
.
Since this is the same DOM element you should rather use CSS classes and keep ID as it is initially. I would suggest (and other would hopefully agree) that changing IDs is bad practice in the first place and should be avoided.
By changing IDs, you're probably ripping the event handler out from under jQuery.
Agree with the previous answers that changing the ID is not the best approach. But, if you want to get your click handlers to work, use the live
function instead of click
:
$('#hideButton').live('click', function() {
// function body same as before
});
$('#showButton').live('click', function() {
// same as before
}
Note that the use of live
will also work if you are trying to change the element's class instead of ID.
精彩评论