从<! - ?php foreach中选择一行:? - >

时间:2015-03-07 16:45:49

标签: php jquery

我正在尝试使用循环foreach中的jquery选择特定行。现在我只是使用一个简单的警报,看看我是否得到了正确的行。问题是,它只选择最后一行,而不是我点击的行。

示例代码:

     <?php foreach ($customers as $c) : ?>
            <tr>
                <td><?php echo $count++; ?></td>
                <td><?php echo $c['firstname'] . " " .  $c['lastname']; ?></td>
                <td><?php echo $c['phone']; ?></td>
                <td><?php echo $c['email']; ?></td>
                <td style="display:none" id="'<?php echo $c['id'] ?>'"> </td>
            </tr>
    <?php endforeach ?>

Jquery致电:

    $('tr td ').click(function(){
    var fn = '<?php echo $c['firstname']; ?>';
    alert(fn);}
    );

2 个答案:

答案 0 :(得分:0)

您可以像bellow

一样访问特定行的列
$('tr.item').each(function() { // selected tr 
        var col1 = $(this).find("td:eq(0) > input").val(); // find the   input field value inside the first column of the row       
        var col2 = $(this).find("td:eq(1) > input").val();}

答案 1 :(得分:0)

这将输出所有td值。 Credits

<html>

    <head>
        <link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" type="text/css" rel="stylesheet" />
    </head>
    <body>

<?php

    $count = 0;
    $customers = array (
                        array('firstname'=>'fname1', 'lastname'=>'lname1','phone'=>'111','email'=>'a@gmail.com','id'=>1),
                        array('firstname'=>'fname2', 'lastname'=>'lname2','phone'=>'222','email'=>'b@gmail.com','id'=>2),
                        array('firstname'=>'fname3', 'lastname'=>'lname3','phone'=>'333','email'=>'c@gmail.com','id'=>3),
                        array('firstname'=>'fname4', 'lastname'=>'lname4','phone'=>'444','email'=>'d@gmail.com','id'=>4),
    );

    ?>
    <table class="table table-bordered">
     <?php foreach ($customers as $c) : ?>
            <tr class="getdetails">
                <td><?php echo $count++; ?></td>
                <td><?php echo $c['firstname'] . " " .  $c['lastname']; ?></td>
                <td><?php echo $c['phone']; ?></td>
                <td><?php echo $c['email']; ?></td>
                <td style="display:none" id="'<?php echo $c['id'] ?>'"> </td>
            </tr>
    <?php endforeach ?>
    </table>
<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
<script>
    $(".getdetails").click(function(){
         $(this).find("td").each(function(){
            console.log($(this).html());
        });
    });
</script>
    </body>
</html>