简体   繁体   English

为了不在javascript中杀死事件处理程序,有什么方法?

[英]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. 我有一个打印功能,允许我打印我的HTML内容。 I can click on the print button fine, but after I click cancel button on the print layout, all my javascript was kill. 我可以点击打印按钮,但在我点击打印布局上的取消按钮后,我的所有javascript都被杀了。 I can't make any action on other button anymore. 我不能再对其他按钮采取任何行动了。

HTML: HTML:

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

Javascript 使用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 最好的解决方案是使用css隐藏/显示元素,但由于某种原因,如果不可能,在脚本中不要替换元素,而是显示/隐藏它们

$(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; 当你使用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来隐藏不想要打印的元素,而不是更改任何HTML元素。 CSS provides rules that only come into effect when the page is printed. CSS提供的规则仅在打印页面时生效。

Something like this should do the trick (you may need to tweek this depending on the structure of your HTML) 像这样的东西应该做的伎俩(你可能需要根据HTML的结构调整这个)

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

Have a read of this or this . 读一读这个这个

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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