试图设置td文字

时间:2017-05-11 01:53:18

标签: javascript jquery html

为什么我的jquery没有设置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/

2 个答案:

答案 0 :(得分: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>
&#13;
&#13;
&#13;

通过使用[0],您将其更改为常规JavaScript元素,从而丢失了jQuery函数。

答案 1 :(得分:1)

您可以使用td:first来获取第一个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>