简体   繁体   English

使用动态变量从tr访问子td

[英]accessing child td from tr using dynamic variable

I have got a problem where I need to access the <td> of <tr> using the jquery .eq() function. 我有一个问题,我需要使用jquery .eq()函数访问<tr><td> Below is the code mentioned please have a look. 下面是提到的代码请看看。

var foundElement = 3;

var values = $(this).children("td:nth-child('" + foundElement + "')").map(function () {...

The above statement gives error for using "foundElement" as variable between the statement. 上面的语句给出了在语句之间使用“foundElement”作为变量的错误。 Please give me a alternate solution or declaration for this. 请给我一个替代解决方案或声明。

You do not need the single quotes around the foundElement . 您不需要在foundElement周围使用单引号。

The selector should be: 选择器应该是:

td:nth-child(3)

or in the string with variable replacement as: 或者在变量替换的字符串中:

$(this).children("td:nth-child(" + foundElement + ")")...

Here is your solution with alternate way...and demo link is as below: 以下是您的替代解决方案......演示链接如下:

Demo: http://codebins.com/bin/4ldqp82 演示: http //codebins.com/bin/4ldqp82

HTML: HTML:

<table cellspacing="3" cellpadding="5" border="1">
  <tr>
    <th>
      col 1
    </th>
    <th>
      col 2
    </th>
    <th>
      col 3
    </th>
    <th>
      col 4
    </th>
    <th>
      col 5
    </th>
  </tr>

  <tr>
    <td>
      data cell 11
    </td>
    <td>
      data cell 21
    </td>
    <td>
      data cell 31
    </td>
    <td>
      data cell 41
    </td>
    <td>
      data cell 51
    </td>
  </tr>

  <tr>
    <td>
      data cell 12
    </td>
    <td>
      data cell 22
    </td>
    <td>
      data cell 32
    </td>
    <td>
      data cell 42
    </td>
    <td>
      data cell 52
    </td>
  </tr>

  <tr>
    <td>
      data cell 13
    </td>
    <td>
      data cell 23
    </td>
    <td>
      data cell 33
    </td>
    <td>
      data cell 43
    </td>
    <td>
      data cell 53
    </td>
  </tr>
</table>

jQuery jQuery的

$(function() {
    $("table tr").each(function() {
        //Check If TD Exists...Then..
        if ($(this).children("td").length > 0) {
            var foundElement = 3;
            alert($(this).children("td:nth-child(" + foundElement + ")").text());
        }
        //OR Alternate Way is
        //Check If TD Exists...Then..
        /*if($(this).find("td").length>0){
                var nthElement=3;
                alert($(this).find("td:eq("+(nthElement-1)+")").text());
       }*/


    });
});

Demo: http://codebins.com/bin/4ldqp82 演示: http //codebins.com/bin/4ldqp82

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM