简体   繁体   中英

Javascript “print contents of div” function repeating the same content

I am attempting to edit a Wordpress plugin for a client which is used to print a coupon by using a custom javascript function to print the contents of a div. This plugin is called by a shortcode:

[print-button target='div#foo']

The target is the css ID of a container div with a jpg of a coupon being the only content. When you click on the generated "print" button then a window opens and brings up a print dialogue for the jpg. With one instance of this plugin on a page it works perfectly, however when you have two or more instances then the only jpg that opens in the new print window is the last one on the page. Here is the plugin code:

add_shortcode("print-button", "sc_show_print_button");

function sc_show_print_button($atts, $content = null){

    $target_element = $atts['target'];

    if($target_element == ''){$target_element = "document.body";}

    $output = "<input id=\"coupon\" type='button' onClick='return pop_print()' value='Print Coupon'/>


    <script type='text/javascript'>
    function pop_print(){
        w=window.open(null, 'Print_Page', 'scrollbars=yes');
        w.document.write(jQuery('$target_element').html());
        w.document.close();
        w.print();
    }
    </script>";


    return  $output;
}

I have echo'd out the $target_element variable at the end of the function and it does list each 'target' variable correctly. I just cannot figure out why only the last instance's image is showing up when you click the "print" button for every other instance. I'm assuming that it's something simple in the javascript that I'm not seeing.

I am not the original author of this plugin, and contacting them is not an option.

Thank you for your help.

Because, when you have more than one instances of "buttons", you have several definition of function "pop_print" with static code. And, of course, the last function always executes.

Try to send target element as argument of function "pop_print".

Example:

add_shortcode("print-button", "sc_show_print_button");

function sc_show_print_button($atts, $content = null){

    $target_element = $atts['target'];

    if($target_element == ''){$target_element = "document.body";}

    $output = "<input id=\"coupon\" type='button' onClick='return pop_print(\'$target_element\')' value='Print Coupon'/>


    <script type='text/javascript'>
    function pop_print(target_element){
        w=window.open(null, 'Print_Page', 'scrollbars=yes');
        w.document.write(jQuery(target_element).html());
        w.document.close();
        w.print();
    }
    </script>";


    return  $output;
}

And, of course, try to replace function from plug-in into external js file.

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