单击一个表中的td并将值与另一个表中的相同td进行比较

时间:2016-01-30 18:04:30

标签: javascript jquery html

以下是我的代码示例。这个想法是,用户可以点击人 - 1下的特定td,并将该统计数据与人员的相同统计数据进行比较。

<div id="person-one">
    <table>
        <tr><td>height</td><td>75</td>
        <tr><td>weight</td><td>180</td>
        <tr><td>age</td><td>35</td>
    </table>
</div>
<div id="person-two">
    <table>
        <tr><td>height</td><td>69</td>
        <tr><td>weight</td><td>155</td>
        <tr><td>age</td><td>29</td>
    </table>
</div>

我认为这将与存储所点击的td的索引有关,但到目前为止我还没能解决。任何帮助赞赏。

2 个答案:

答案 0 :(得分:0)

类似的东西:

p1 = document.getElementById('person-one').children[0].children[0].children
p2 = document.getElementById('person-two').children[0].children[0].children
console.log(p1)


var findOthersParam = function(param) {
    for(var i=0; i<p2.length; i++) {
    if (p2[i].children[0].innerHTML == param) 
        return p2[i].children[1].innerHTML
  }
}
for (var i=0; i<p1.length; i++) {
    p1[i].onclick = function() {
    alert("this person's "+ this.children[0].innerHTML 
       +' is '+ this.children[1].innerHTML 
       +" and the other's is "+ findOthersParam(this.children[0].innerHTML))
  }
}

https://jsfiddle.net/grabantot/n650x3o6/1/

答案 1 :(得分:0)

我已经添加到您的HTML中,因此有太多反馈意见。

<div class="feedback"></div>

我已按原样离开您的HTML结构,但会添加另一个可以更广泛地进行改进的答案。

使用Javascript:

// Place we're going to give feedback
var feedback = $('.feedback');

    $('tr').on('click.compare', function (){

  // Index which we need to make "1 base"
  var index = $(this).index() + 1;

        // Empty the feedback
  feedback.empty();

  // Remove all current selected TRs
  $('tr').removeClass('compare')

  // Collection of TRs being compared
  // In this instance, we will find two TRs because we have two tables
  // Both TRs will have the same index - and if the table layout is
  // matching then that means we're comparing the same categories
  var comparing = $('tr:nth-of-type(' + index + ')');

        // Number of actual TRs we've found so we can use conjunctives
  // in our loop
        var rows = comparing.length;

        // Loop through each TR in the collection
  // Note: Named functions are nicer
        comparing.each(function processRow (index, row) {

    // Make some vars so we know what is being compared
            var title = $('td:nth-of-type(1)', row).html();
    var val = $('td:nth-of-type(2)', row).html();

            // Append our vars to the "feedback" DIV
            feedback.append(title, " ", val)

            // Append the word "and" at the end as we know
    // there will be another one
            if (index < (rows-1)) {
        feedback.append(' and ')
    }

  }) // End of loop

}); // End of event

CSS:

table { margin-bottom: 20px; }
table td { width: 70px; border: 1px solid black; }
tr.compare { background: red; color: white; }

工作jsFiddle:https://jsfiddle.net/likestothink/o2y2pn65/1/