Get Value of nearest HTML thead element when clicking on td cell

后端 未结 1 1859
我在风中等你
我在风中等你 2021-01-23 12:28

I have an HTML table which looks like this:

1条回答
  •  被撕碎了的回忆
    2021-01-23 12:57

    Since you have colspans involved one way is create an array for all the headings text. On page load go through all the and get the colspan value and use that value to push text into the headings array for each column spanned.

    Then when you click a use it's index within cells on that row to get the associated heading text from the headings array

    // add some cell text for demo
    demoInit();
    
    let spanHeadings = [];
    
    $('thead th[colspan]').each(function() {
      const colspan = +this.colSpan,
        heading = $(this).find('.theader-text-nonstrong').text();
      // create as many headings as colspan length
      spanHeadings.push.apply(spanHeadings, Array(colspan).fill(heading));
    });
    
    
    $('#reservationtable tbody td').click(function() {
      const tdIdx = $(this).index() - 1;// subtract for the left ``
      const heading = spanHeadings[tdIdx];
      console.clear()
      console.log('heading: ', heading)
    });
    
    function demoInit() {
      $('td:empty').text(function(i) {
        return 'Cell ' + (i + 1)
      });
    
    }
    td {
      border: 1px solid #ccc;
      padding: 4px
    }
    
    table {
      border-collapse: collapse
    }
    
    
    Span 1 Span 2
    Span 3
    Span 4
    Zeit Platz 1 Platz 2 Platz 3 Platz 1 Platz 2 Platz 3 Platz 1 Platz 2 Platz 3 Platz 1 Platz 2 Platz 3
    08:00
    09:00

    0 讨论(0)
提交回复
热议问题