2017-05-11 28 views
0

为什么我的jquery没有设置td?试图设置td文本

$("td")[0].text("hello"); 

查找下面前:

var array = [1,2,3,4,5,6]; 
var counter = 0; 
while(array.length) { 
    var index = Math.floor(Math.random()*array.length); 
    //alert(array[index]); // Log the item 
    //$('td').index(counter).html(index); 
    $("td")[0].text("hello"); 
    array.splice(index, 1); // Remove the item from the array 
    counter++; 
    //alert(array); 
} 

的jsfiddle https://jsfiddle.net/o3c66fz8/4/

回答

3

使用$("td").eq(0).text("hello");代替。

var array = [1,2,3,4,5,6]; 
 
    var counter = 0; 
 
    while(array.length) { 
 
      var index = Math.floor(Math.random()*array.length); 
 
     //alert(array[index]); // Log the item 
 
     //$('td').index(counter).html(index); 
 
     $("td").eq(index).text("hello"); 
 
     array.splice(index, 1); // Remove the item from the array 
 
     counter++; 
 
     //alert(array); 
 
    }
td 
 
{ 
 
padding: 2em; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<table border="1"> 
 
<tr> 
 
<td>r1c1</td><td>r1c2</td><td>r1c3</td> 
 
</tr> 
 
<tr> 
 
<td>r2c1</td><td>r2c2</td><td>r3c3</td> 
 
</tr> 
 
</table>

使用[0]你将其更改为常规的JavaScript元素,从而失去了jQuery功能。

1

您可以使用TD:率先拿到了首个TD

var array = [1,2,3,4,5,6]; 
 
    var counter = 0; 
 
    while(array.length) { 
 
      var index = Math.floor(Math.random()*array.length); 
 
     //alert(array[index]); // Log the item 
 
     //$('td').index(counter).html(index); 
 
     $("td:first").text("hello"); 
 
     array.splice(index, 1); // Remove the item from the array 
 
     counter++; 
 
     //alert(array); 
 
    }
td 
 
{ 
 
padding: 2em; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<table border="1"> 
 
<tr> 
 
<td>r1c1</td><td>r1c2</td><td>r1c3</td> 
 
</tr> 
 
<tr> 
 
<td>r2c1</td><td>r2c2</td><td>r3c3</td> 
 
</tr> 
 
</table>