如何使用jQuery从HTML隐藏字段中获取文本

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

本文关键字:字段 获取 取文本 隐藏 HTML 何使用 jQuery      更新时间:2023-09-26

我需要使用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>'))
      });(...)

和后面的值。IDMessage是隐藏的,我必须再次获取它的值,然后传递到另一个地方。代码如下:

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

不幸的是,type变量总是给出0。当我将.val()更改为.text().html().toString()时,它可以工作,但我无法从隐藏字段中获得值。

我该怎么做?

试试这个,我想这就是你想要的。在本例中,我向您展示了如何从static元素中获取hidden field values,以及如何在dynamic环境中获取隐藏字段值。

注意:当您想要从隐藏字段中分配和获取值时,最佳实践是使用 input 字段type="hidden"

试试下面两个例子。好运。

<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>