开发者

storing variables in html and using text()

开发者 https://www.devze.com 2023-03-04 02:25 出处:网络
I have a particular scenario where I need a file name, not once but twice, because I pass the variable to an ASP.NET MVC controller. Is it a good idea to either store the file n开发者_运维技巧ame in a

I have a particular scenario where I need a file name, not once but twice, because I pass the variable to an ASP.NET MVC controller. Is it a good idea to either store the file n开发者_运维技巧ame in a DOM element like a span or div, and getting the value by using jQuery's .text() function? Or would a better approach be to work with JSON-like objects that are initialized and then continuously manipulated?

The question however remains. Is it a good or bad idea to store variables in HTML DOM elements?


As @Atticus said, it's fine to do it either way, and I'll do both depending on what I need the data for: If it's specifically tied to the element, I'll store it on the element; if it's more general to the page, I'll pass back an object using JSON notation.

When storing data on DOM elements, you don't need to store them as text within the element. You can use data-* attributes instead. These are valid as of HTML5 and work in all browsers right now. The only downside is that if you're using validation as part of your workflow, and you're not yet using HTML5 to validate (and that wouldn't be surprising, the validator isn't quite ready, what with the spec still being rather in flux!), they don't validate in HTML 4.01 or below. But browsers are fine with them, this is one of the areas where HTML5 is codifying (and reigning in) current practice, rather than innovating.


Either one works, and it's fine to store data in a DOM. It more so depends on the complexity of the operation you are trying complete, which sounds simple -- storing file names. I think you should be fine doing it this way. Storing in JSON object works too, I would go with whatever fits your structure best and which ever works easier with your client/server handshake.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号