简体   繁体   中英

jQuery: Hide tr of child td that contains ul + print?

I have a <table> where certain <td> contain <ul> and I want it when a specific button is clicked, two things occur:

  1. Parent <tr> of children <td> that contain a <ul> are hidden
  2. The window is printed after step 1 is executed, so that <tr> containing <ul> are hidden on the printed sheet

http://jsfiddle.net/emturano/S9YWL/

HTML:

<table id="todo-list">
    <tr>
        <td>Entry No UL 1</td>
    </tr>
    <tr>
        <td>Entry No UL 2</td>
    </tr>
    <tr>
        <td>
            <ul>I SHOULD BE HIDDEN WHEN PRINTED</ul>
        </td>
    </tr>
    <tr>
        <td>Entry No UL 4</td>
    </tr>
</table><p>

Click to print

jQuery:

function () {
    $('#followup_a').click(followup);
});

function followup() {
    $('#todo-list tr:has(td:has(ul))').hide();
    window.print();
}

First problem I see is the line function () { . That is improper syntax. I think what you mean to do is the document ready method of which I'll show in my answer.

Remove the onClick="window.print()" from your link and then change your JS to the following:

$(function(){ // document . ready call
    $('#followup_a').on("click", function(e) {
        //  if href does not contain `javascript:void(0)` then use
        //  e.preventDefault(); // to prevent default link action
        $("#todo-list tr").filter(function(i) { return $(this).find("> td ul").length > 0 }).hide();
        window.print();
    });
})

What this does:

  • .filter() is a nice jquery method that allows you to call on a group of jQuery elements like $("#todo-list tr") , which would normally return all table rows, and filter the result object down based on what information returns true.
    • although $('#todo-list tr:has(td:has(ul))') should do roughly the same thing
  • href="javascript:void(0)" is one way to prevent default link action, or, within the click event you could call on event.preventDefault()

Could also be written as:

function followup(e) {
    $("#todo-list tr").filter(function(i) { return $(this).find("> td ul").length > 0 }).hide();
    window.print();
}

$(function(){ // document . ready call
    $('#followup_a').on("click", followup);
})

Demo

You may achieve the same results just defining specific CSS for Print media:

@media print
  {
  td.noprint {display:none;}
  }

(Just a small example, adapt to your specific needs.)

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