jQuery 比隐藏字段更好的方法来在 html 中存储数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18013337/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 20:21:46  来源:igfitidea点击:

Better approach than hidden field to store data in html

javascriptjqueryhtmlajax

提问by nubinub

I'd like to know if a better approach exists to store data in html content.
At the moment I got some values stored in my html file using hidden field. These values are generated by code behind.

我想知道是否存在更好的方法来将数据存储在 html 内容中。
目前,我使用隐藏字段将一些值存储在我的 html 文件中。这些值是由背后的代码生成的。

Html:

网址:

<input type="hidden" id="hid1" value="generatedValue1" />
<input type="hidden" id="hid2" value="generatedValue2" />

And therefore I get those values on client side using jquery, in order to pass them to an ajax request.

因此,我使用 jquery 在客户端获取这些值,以便将它们传递给 ajax 请求。

JQuery

查询

$.ajax({
  data:{
     var1 : $('#hid1').val(),
     var2 : $('#hid2').val()
  }
);

So is this the correct way to do this, or does it exist a smoother solution to achieve the same result? Since I don't need these values to be posted on page submit the input hiddenis probably gross.

那么这是执行此操作的正确方法,还是存在更流畅的解决方案来实现相同的结果?由于我不需要将这些值发布在页面上,因此提交input hidden可能很糟糕。

采纳答案by T.J. Crowder

If you don't need those in a form, then just make them variables in your JavaScript. To output them, encode them via the JavaScriptSerializerclass:

如果您不需要表单中的那些,那么只需在您的 JavaScript 中将它们设为变量即可。要输出它们,请通过JavaScriptSerializer对它们进行编码:

<%
    // Presumably somewhere in your C# code...
    JavaScriptSerializer serializer = new JavaScriptSerializer();
%>
<script>
var hid1 = <%= serializer.Serialize(valueForHid1) %>;
var hid2 = <%= serializer.Serialize(valueForHid2) %>;
</script>

(See note below about globals.)

(请参阅下面关于全局变量的注释。)

Using them later:

稍后使用它们:

$.ajax({
  data:{
     var1 : hid1,
     var2 : hid2
  }
);

Globals: As shown there, hid1and hid2end up as globals (on most browsers, they do when you use hidden fields as well). I recommend not using globals, but instead wrapping everything in scoping functions:

全局变量:如图所示,hid1hid2最终作为全局变量(在大多数浏览器上,当您使用隐藏字段时也会这样做)。我建议不要使用全局变量,而是将所有内容都包装在作用域函数中:

(function() {
    var hid1 = <%= serializer.Serialize(valueForHid1) %>;
    var hid2 = <%= serializer.Serialize(valueForHid2) %>;

    // ....    

    $.ajax({
      data:{
         var1 : hid1,
         var2 : hid2
      }
    );
})();

If for some reason you haveto use a global, use just one:

如果由于某种原因必须使用全局变量,请仅使用一个:

var myOneGlobal = {
    hid1: <%= serializer.Serialize(valueForHid1) %>,
    hid2: <%= serializer.Serialize(valueForHid2) %>
};

Using that later:

稍后使用:

$.ajax({
  data:{
     var1 : myOneGlobal.hid1,
     var2 : myOneGlobal.hid2
   }
);

You can output an entire object graph to one variable (perhaps myOneGlobal) with the serializer:

您可以myOneGlobal使用序列化程序将整个对象图输出到一个变量(可能):

<script>
var myOneGlobal = <%= serializer.Serialize(objectWithData) %>;
</script>

回答by Chococroc

What I usually do is adding the values as data-attributes to the html form:

我通常做的是将值作为数据属性添加到 html 表单中:

<form data-field1="generatedValue1" data-field2="generatedValue2">
...
</form>

And then, retrieve them with jQuery:

然后,使用 jQuery 检索它们:

... 
$form = $( my_selector_to_take_the_form );

data:{
     var1 : $('form').attr('data-field1'),
     var2 : $('form').attr('data-field1')
  }

With this, you won't post any hidden field

有了这个,您将不会发布任何隐藏字段

回答by moritzpflaum

You can use the new HTML5 "data" attributes. (http://html5doctor.com/html5-custom-data-attributes/)

您可以使用新的 HTML5“数据”属性。( http://html5doctor.com/html5-custom-data-attributes/)

Your codebehind section would do something like this:

您的代码隐藏部分将执行以下操作:

<ul data-listname="{put name here}">
    <li data-key="{put key here}>
        Item1 
    </li>
</ul>

And then in your jQuery you can do:

然后在您的 jQuery 中,您可以执行以下操作:

var firstId = $('li').first().data('id');
var list = $('ul').data('listname');

Make sure to only use lowercase after the data-I have found, that it will not work correctly otherwise. You can also set the data like this:

确保在data-我找到后只使用小写字母,否则它将无法正常工作。您还可以像这样设置数据:

$('#something').data('smthgnelse', 'Hi there');

回答by Hyman Black

You should use the HTML5 data attribute.

您应该使用 HTML5 数据属性。

i.e <a href="#" data-YOURKEY="YOUR-VALUE">My Link</a>

IE <a href="#" data-YOURKEY="YOUR-VALUE">My Link</a>

You can easy access this attributes i.e with jQuery

您可以轻松访问此属性,即使用 jQuery

$(".mylink").attr("data-YOURKEY");

John Resig explained it well: http://ejohn.org/blog/html-5-data-attributes/

John Resig 解释得很好:http: //ejohn.org/blog/html-5-data-attributes/

Please also read the specs from HTML5-Doctor http://html5doctor.com/html5-custom-data-attributes/

另请阅读 HTML5-Doctor http://html5doctor.com/html5-custom-data-attributes/的规范

..and if you like to go a bit deeper: http://www.w3.org/html/wg/drafts/html/master/dom.html#embedding-custom-non-visible-data-with-the-data-*-attributes

..如果你想更深入一点:http: //www.w3.org/html/wg/drafts/html/master/dom.html#embedding-custom-non-visible-data-with-the-数据-*-属性