简体   繁体   中英

jquery add event for custom rows does not work

I am trying to add click events only to the columns in a row that has some text in the first column. For the first row the click events should hide the rows that contain "1/" in the first column. Here is my html table:

<table class="results">
<tr>
<td>1</td>
<td>Distribution_Approval_Archive_WorkFLow</td>
<td>0h:2m:59s:845ms</td>
<td><font color="red">TestFail</font></td>
</tr>

<tr>
<td>1/1</td>
<td>MyLogin</td>
<td>0h:0m:8s:298ms</td>
<td><font color="green">TestCasePass</font></td>
</tr>

<tr>
<td>1/2</td>
<td>OpenEFlowEnterprise</td>
<td>0h:0m:13s:912ms</td>
<td><font color="green">TestCasePass</font></td>
</tr>

<tr>
<td>2</td>
<td>Distribution_Approval_Archive_WorkFLow</td>
<td>0h:2m:59s:845ms</td>
<td><font color="red">TestFail</font></td>
</tr>

<tr>
<td>2/1</td>
<td>MyVismaLogin</td>
<td>0h:0m:6s:223ms</td>
<td><font color="green">TestCasePass</font></td>
</tr>

<tr>
<td>2/2</td>
<td>OpenEFlowEnterprise</td>
<td>0h:0m:5s:158ms</td>
<td><font color="green">TestCasePass</font></td>
</tr>

</table>

And here is my jQuery for adding the events:

for (i=1; i <= $(".results td:nth-child(1):not(:contains('/'))").parent().length; i++){
    $($(".results td:nth-child(1):not(:contains('/'))").parent()[i-1]).children().click(function(){
        $('.results td:nth-child(1):contains("'+ i +'/")').parent().slideToggle("fast");
    })
}

Can you help fix the jQuery code?

Never bind events in loops,try the following

$('tr').find('td:first-child()').not(':contains("/")').parent().click(function(e){
   var index = $(this).find('td:first-child()').text().split('/')[0];
   $('td:contains("'+index+'/")').parent().slideToggle("fast");
});

You can code:

$(".results td:nth-child(1):not(:contains('/'))").on("click", function(){
      var i = $(this).text().split('/')[0];
      $('.results td:nth-child(1):contains("'+ i +'/")').parent().slideToggle("fast");
     });

Final code that I used for this ( http://jsfiddle.net/danginkgo/jr5qvqj3/ ):

$('.results tr td:first-child:not(:contains("/"))').parent().click(function(){
  var i = $.trim($(this).find('td:first-child').text().split('/')[0]);
  $('.results td:first-child:contains("'+ i +'/")').parent().slideToggle("fast");
});

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