簡體   English   中英

如何通過使用jQuery從HTML的隱藏字段中獲取文本

[英]How to get text from hidden field in HTML by using jQuery

我需要使用jQuery從隱藏字段中獲取值。 我的代碼隱藏了一些值,如下所示:

(...)$.each(response, function (index, value) {
     $('#notiContent').append(
          $('<li>Nowa wiadomosc : ' + value.Subject + 
          ' od ' + value.Receive + ' data ' + ToJavaScriptDate(value.Date) 
           + ' </li>' + '<li style = "display: none;">' + value.IDMessage + '</li>'))
      });(...)

在隱藏了value.IDMessage之后,我必須再次獲取其值,然后傳遞到另一個地方。 代碼如下:

          (...)$("#notiContent").delegate('li', 'click', function () {
            var type = $(this).val(); (...)

不幸的是, type變量始終提供0。 當我將.val()更改為.text().html().toString()它可以工作,但是我無法從隱藏字段中獲取該值。

我怎樣才能做到這一點?

嘗試了這一點,我覺得這是你want.in這個例子中我向您展示如何讓hidden field valuesstatic元素,如何讓隱藏字段的值dynamic環境。

注意:當您要分配隱藏字段的值並從中獲取值時,最佳做法是使用 類型為“ hidden”的 input 字段

請嘗試以下兩個示例,並嘗試一下。

 <html> <head></head> <title></title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> <body> <h2>Get the value from static element ---> Note : to get the hidden value, best practice is to use <span style="background-color:red;color:white;">input</span> field</h2> <div id="notiContentone"> <li style="cursor:pointer;">Nowa Wiadomosc bla bla bla</li> <input type="hidden" id="myhidden" value="give_your_value_here"> </div> <br><br><br><hr> <h2>Get the value from dynamic elements</h2> <div id="notiContentwo"></div> </body> <script type="text/javascript"> //get the value from static element implement $("div#notiContentone li").click(function(){// in here we choose the li element inside the notiContentone var hiddenValue = $("#myhidden").val(); //here we get the assinged value for the hidden field. alert(hiddenValue); }); //get the value from dynamic elements $(document).ready(function(){ var createelement_li = $('<li style="cursor:pointer;color:orange;background-color:pink;width:400px;">Nowa Wiadomsc bla bla bla </li>'); var createelement_hidden_input = $('<input type="hidden" id="myhiddentwo" value="dynamically_added_value_here">'); $("#notiContentwo").append(createelement_li); $("#notiContentwo").append(createelement_hidden_input); $("div#notiContentwo li").click(function(){ var gettheHiddenValue = $("#myhiddentwo").val(); alert(gettheHiddenValue); }); }); </script> </html> 

暫無
暫無

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

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