开发者

How can I restructure this small bit of jQuery so that it works properly

I have a link as follows:

<div id="div_1">
    <a href="#" id="link_1"><img height="64" src="/images/image.png" width="64" />Link1</a>
</div>

I set the click event using jQuery as follows:

var old_html;
$('#link_1').click(function() {     
    old_html = $('#div_1').html();
    $('#div_1').html('<input type="button" value="Cancel" id="cancel_button">');
    $('#cancel_button').mouseup(function(){
        $('#div_1').html(old_html);
    }); 
});

I can click on the link, and the div's html is replaced by the cancel button. I can then click on the cancel button, and the html reverts back to how it originally way.

But if I then click on the link again, nothing happens. The click event is no longer attached. How should I chang开发者_运维百科e the code so that I can switch back and forth by clicking the link and then the cancel button as many times as I want? Thanks for reading.


Use the $().toggle( handler(event), handler(event) ) method: http://api.jquery.com/toggle-event/

Sample usage:

$('#target').toggle(function() {
    alert('First handler for .toggle() called.');
}, function() {
    alert('Second handler for .toggle() called.');
});

The functions take turns executing when #target is clicked.


Try this version instead. Here we are not refreshing DOM by changing its html content. Instead just managing visibility of elements on click of it.


use onClick on the a tag


The click handler is removed when you replace the HTML. You have to set it again after setting the old HTML:

function showCancelButton() {
    var old_html;
    old_html = $('#div_1').html();
    $('#div_1').html('<input type="button" value="Cancel" id="cancel_button">');
    $('#cancel_button').mouseup(function(){
        $('#div_1').html(old_html);
        $('#link_1').click(showCancelButton);
    });
}

$(document).ready(function() {
    $('#link_1').click(showCancelButton);
});

But generelly, I would also recommend putting both the link and the cancel button into your HTML and just toggling their respective visibility:

function toggleLinkCancel() {
    $('#link_1').toggle();
    $('#cancel_button').toggle();
}

$(document).ready(function() {
    $('#link_1').click(toggleLinkCancel);
    $('#cancel_button').mouseup(toggleLinkCancel);
});

Your HTML would have to contain the cancel button, hidden via CSS by default.

This way your content and code are separated, which is easier to maintain in the long run.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜