简体   繁体   中英

What is the way in order not to kill event handler in javascript?

I have a print function which is allow me to print my content of HTML. I can click on the print button fine, but after I click cancel button on the print layout, all my javascript was kill. I can't make any action on other button anymore.

HTML:

<div id="printArea">
<p>Hello World</p>
</div>
<button type="button" id="printer">Print</button>

Javascript

$(document).on('click', '#printer',function(event){
        event.preventDefault();
        var printContents = document.getElementById("printArea").innerHTML;
        var originalContents = document.body.innerHTML;
        document.body.innerHTML = printContents;
        window.print();
        document.body.innerHTML = originalContents;
    });

I want to click on print button and then go back by clicking cancel button, and also other button still can take action as usual.

Any help would be very appreciate.

The best solution is to use css to hide/show element, but for some reason if that is not possible, in your script don't replace the elements but show/hide them

$(document).on('click', '#printer', function (event) {
    event.preventDefault();
    var $print = $("#printArea");
    //hide teh contents of the page
    $(document.body).wrapInner('<div style="display: none"></div>');
    //move a copy of the print area to the body and show it
    var $div = $('<div />').append($print.clone().contents()).appendTo(document.body);
    window.print();
    //remove the temporary print display
    $div.remove();
    //show back the original content
    $(document.body).children().contents().unwrap();
});

Demo: Fiddle

When you use document.body.innerHTML = originalContents; it create new elements that don't have any event functions attached to them.

It would be better to use CSS to hide the elements that you don't want printed rather than changing any HTML elements. CSS provides rules that only come into effect when the page is printed.

Something like this should do the trick (you may need to tweek this depending on the structure of your HTML)

@media print {
  body * { display:none; }
  #printArea { display:block; }
}

Have a read of this or this .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM