Need help, click
works immediately when the page loads. I read and tried different options, but it does not help. I can not find the right solution.
$.ajax({
url: '/print',
success: function (response) {
function printContent(el) {
var restorepage = document.body.innerHTML;
var printcontent = document.getElementById(el).innerHTML;
document.body.innerHTML = printcontent;
window.print();
document.body.innerHTML = restorepage;
}
response.forEach(function (element, index) {
$('div.h4').after(
'<div id="print_' + index + '">' +
'<p>' + element + '</p>' +
'</div>' +
'<button id="button_' + index + '">Print</button>'
);
var el = document.getElementById('button_' + index);
el.addEventListener('click', printContent('print_' + index), false);
})
}
});
HTML:
<div class="h4"></div>
Your issue is on el.addEventListener('click', printContent('print_' + index), false);
you are immediately calling the function instead replace above mentioned line as below
el.addEventListener('click', printContent, false);
and change your printContent
function as below
function printContent() {
var el = $(this).prev().attr('id');
var restorepage = document.body.innerHTML;
var printcontent = document.getElementById(el).innerHTML;
document.body.innerHTML = printcontent;
window.print();
document.body.innerHTML = restorepage;
}
I haven't tested it but it should work. Please let me know if it does not work.
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.