隐藏输入与HTML5数据属性 [英] Hidden inputs vs HTML5 data attributes

查看:127
本文介绍了隐藏输入与HTML5数据属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近一直困扰我的是使用 HTML5数据属性,何时适用使用它们。
$ b

通常,在执行一些AJAX调用到我的服务器的页面上,我需要 ID 这是正在查看的页面的代表。我目前一直在页面上隐藏< input> 元素,然后访问并存储在jQuery文档顶部的JS变量中调用。



我一直在考虑将它移动到body元素上的 data-id 属性,其中I然后将使用 $('body')。data('id');



访问jQuery使用HTML5数据属性有什么优势,反之亦然?性能?安全? 最佳实践?

我的理解是所有浏览器都可以访问数据属性,因此处理IE不是问题。



由于这些属性并未提交给服务器在POST中,您需要记住JavaScript禁用的浏览器中会发生什么情况。如果您的页面也应该能够正常降级并在必要时通过传统表单提交来执行相同的AJAX请求的功能,那么仍然需要隐藏字段。



,当他们有意义时,我是数据属性的忠实拥趸,特别是在严格的应用类型网站中,您可以安全地使用JavaScript。例如,标记具有data-id属性的表格行比在其单元中填充隐藏字段更好。尤其是与jQuery对 .data()方法的良好数据属性支持相结合,这使得在隐藏字段可能有点混乱的情况下提供干净,直观的代码。


Something that's been bugging me recently is the use of HTML5 data attributes and when is the appropriate to use them.

Typically, on a page that performs a number of AJAX calls to my server, I require the ID that is representative of the page being viewed. I've currently been storing this in a hidden <input> element on the page, which is then accessed and stored in a JS variable at the top of my jQuery doc ready call.

I've been considering moving it to a data-id attribute on the body element, which I then would access in jQuery using $('body').data('id');.

Is there any advantages to using HTML5 data atttributes or visa versa? Performance? Security? "Best-Practices"?

It's my understanding that data attributes are accessible by all browsers so dealing with IE isn't a concern.

解决方案

One of the main drawbacks is accessibility.

Since those attributes aren't submitted to the server in POSTs, you'll need to keep in mind what happens in JavaScript-disabled browsers. If your page should also be able to degrade gracefully and perform those same AJAX-requested features via traditional form submissions if necessary, a hidden field will still be required.

That said, I'm a big fan of data- attributes when they make sense, especially in strictly "application" type sites where you can safely mandate JavaScript. It's a lot nicer to tag a table row with a data-id attribute than stuff a hidden field in one of its cells, for example. Especially coupled with jQuery's nice data- attribute support for the .data() method, that makes for clean, intuitive code in situations where hidden fields can be a bit messy.

这篇关于隐藏输入与HTML5数据属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆