繁体   English   中英

如何获取最后一个元素的ID?

[英]How to get the id of the last element?

我有产品列表,使用下面的代码

<table id="product">
    <thead>
        <tr> 
            <th style="width:30%;">Item Name</th>
            <th style="width:11%;">Price</th>
            <th style="width:11%;">Qty</th>
        </tr>
    </thead>
    <tbody id="cart_contents">
        <?php $i=1;
            foreach($cart as $line=>$item)
            {
            ?>
                <tr>
                    <td style="align:center;"><?php echo $item['name']; ?></td>
                    <td><input type="text"  id="price_<?php echo $i;?>" value="<?php echo $item['price']; ?>" name="price"></td>
                    <td id="qnty"><input type="text"  id="quantity_<?php echo $i;?>" value="<?php echo $item['quantity']; ?>" name="quantity"></td>
                </tr>
            <?php 
                $i++;
            }
        ?>
    </tbody>
</table>

我需要编辑最后添加的产品的数量和价格字段。

<table width="297px" style="float:left" class="CSSTableGenerator">
    <tr>
        <td onclick="click_quantity();"><a href="javascript:void(0);">Qty</a></td>      
        <td onclick="click_price();"> <a href="javascript:void(0);" >Price</a></td>
    </tr>
</table>
function click_quantity(){   
    $("#table register").find("td qnty").each(function(){
        var id = $(this).attr("id");
        alert(id);
    }) 
}

单击“ Qty链接后,如何获取最后一个数量字段的ID?

我已经尝试了一些代码,但是无法获取最后一个元素的ID。

EX:ID名称为quantity_1, quantity_2, quantity_3, quantity_4

如何获得quantity_4 (最后一个元素的ID)?

HTML

<table id="product">
<thead>
<tr> 
    <th style="width:30%;">Item Name</th>
    <th style="width:11%;">Price</th>
    <th style="width:11%;">Qty</th>
</tr>
</thead>
<tbody id="cart_contents">
<?php $i=1;
foreach($cart as $line=>$item)
{
?>
<tr>
    <td style="align:center;"><?php echo $item['name']; ?></td>
    <td>
        <input type="text"  id="price_<?php echo $i;?>" value="<?php echo $item['price']; ?>" name="price"/>
    </td>
    <td class="qnty">
         <input class="qnty_input" type="text"  id="quantity_<?php echo $i;?>" value="<?php echo $item['quantity']; ?>" name="quantity"/>
    </td>
</tr>
 <?php 
 $i++;
  } ?>
</tbody>
</table>

JS代码

  function click_quantity(){
    var id = $("#cart_contents tr:last-child .qnty_input").attr("id");
    // rest of your logic
  }

1)您正在循环使用相同的ID,这是无效的;

2)我认为您的js错误,请使用: $("#register").find("#qnty") ,但必须为find('.qnty')

试试这个。

var last_id = $( 'table tbody tr td:last-child').attr( 'id' );

要获取表中的最后一行(td),您可以使用此代码,

$('table tbody tr td:last-child')

为了获得最后一个子元素,您可以使用尝试使用jquery的last属性

$("#cart_contents td:last").find('input[type=text]').attr('id');
$("#cart_contents td:last")

使用它,您将在每一行中找到最后一列,因此您必须使用

$("#cart_contents tr:last-child td.qnty")

暂无
暂无

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

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