簡體   English   中英

jQuery獲取類的最新實例的值

[英]Jquery get the value of the most recent instance of a class

我如何從該表單實例中獲取名為userID的類的值? 我無法序列化表單,因為表單本身沒有任何唯一標識符。

<form method="post">
       <input type="hidden" name="userID" class="userID" value="<? echo $id; ?>" >
       <input type="hidden" name="imageID" class="imageID" value="<? echo $row['newest_image']; ?>" >
       <input type="button" style="margin-top:10px" name="delete_standard" class="delete_standard_btn" value="Delete">
</form>

目前我正在使用

var image_id = $(this).prev('.imageID').val();
var user_id = $(this).prev('.userID').val();

如果我以形式交換掉隱藏的輸入,這使我的imageID可以,但沒有userID,我可以得到userID而不是imageID。

使用prevAll('.userID')而不是prev('.userID') prev僅查看緊鄰的前一個同級, prevAll查看所有先前的同級, prevAll順序返回它們(最優先)。 由於最接近的是第一個,因此在其上調用val()將為您提供最接近的匹配同級的值。

例如:

var image_id = $(this).prevAll('.imageID').val();
var user_id = $(this).prevAll('.userID').val();

如果$(this)是表單,則使用.find()。

$('.userID', this).val();
// or
$(this).find('.userID').val();

如果它是按鈕元素,請使用.prevAll()而不是.prev()。

$(this).prevAll('.userID').first().val();

當你提交一個表單的jQuery,您的上下文this被設置為當前表單元素。 因此,您可以執行以下操作:

$('form').on('submit', function (e) {
    var $this = $(this),
        image_id = $this.find('.imageID'),
        user_id = $this.find('.userID');
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM