簡體   English   中英

如何在jQuery中獲取動態隱藏ID值?

[英]How to get dynamic hidden id value in jquery?

在html中,我使用了帶有動態ID的隱藏字段。

<a><input type="hidden" name="edit_hid" id="edit_'+id+'" value="123" />something 1</a>

<a><input type="hidden" name="edit_hid" id="edit_'+id+'" value="456" />something 2</a>

<a><input type="hidden" name="edit_hid" id="edit_'+id+'" value="789" />something 3</a>

在這里,我正在jquery中獲取上述隱藏元素的ID。

var hiddenID = $('input[name$="edit_hid"]').attr('id');
alert(hiddenID );

每當我單擊超鏈接時,東西1,東西2,東西3,我總是得到id為edit_0

如何獲得每個超鏈接的動態ID? 這樣我就可以獲得這些動態ID的值。

一種解決方案是在jquery選擇器中使用:hidden

 $("a").on("click", function(){ alert($(":hidden", this).val()); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <a><input type="hidden" name="edit_hid" id="edit_'+id+'" value="123" />something 1</a> <a><input type="hidden" name="edit_hid" id="edit_'+id+'" value="456" />something 2</a> <a><input type="hidden" name="edit_hid" id="edit_'+id+'" value="789" />something 3</a> 

像這樣的事情可能會起作用,您是否更清楚,這些鏈接是如何動態添加的,這可能會影響它應該如何工作?

<script>
     $(function(){
       $(".hidden").click(function(){
         var a = $(this).attr("id");
       alert(a);
       });
       });
    </script>

您正在使用$('input[name$="edit_hid"]')返回集合(數組)

當您使用attr('id') ,它將返回第一個[0] (id = 0)

所以你應該使用

var a=$('input[name$="edit_hid"]')[0].attr('id');
var b=$('input[name$="edit_hid"]')[1].attr('id');
var c=$('input[name$="edit_hid"]')[2].attr('id');

檢查集合$('input[name$="edit_hid"]').length length屬性(應為3)

我認為您不需要隱藏輸入的點擊功能。

嘗試這個。

   $(document).ready(function() {
     var hiddenID;
      $('input').live("focus", function() {
        hiddenID = $(this).attr('id');
        alert(hiddenID );
        });
   });

`focus將僅綁定到調用時存在的元素。

live()將一個函數綁定到所有現有元素以及以后添加到DOM中的任何元素的事件。

希望它能對您有所幫助:)

暫無
暫無

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

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