HTML id 友好且区分大小写的简单哈希函数
我从外部源获取一些字符串,并将它们显示在页面上的 span
中。
我需要一种方法来使用 document.getElementById()
或 jQuery 的 $("#XXXX")
返回这些字符串,因此随着每个字符串我得到某种一个标识符,我使用该标识符作为 span
的 ID。
问题是我得到的标识符可能包含像 +
这样的字符。不允许将其作为 id
属性的值 http://www .w3schools.com/tags/att_standard_id.asp 此外,这些标识符区分大小写。所以我想到使用像 SHA 或 MD5 这样的散列函数来散列我得到的标识符,然后将它们用作我的跨度的 id,然后我可以再次应用散列函数来查找我的元素。
对于如此简单的功能来说,这似乎很复杂。有更好的方法吗?或者也许是一个非常简单的哈希函数,可以保证 id 友好的字符和区分大小写? (HTML 的 id
不区分大小写,这是考虑哈希函数的另一个原因)
I get some strings from an external source, and I display them in span
s on my page.
I need a way to get back to those strings using document.getElementById()
or jQuery's $("#XXXX")
, so along with each string I get some sort of an identifier, I use that identifier as the ID of the span
.
The problem is that the identifier I get could contain chars like +
for example. Which is not allowed as a value for the id
attribute http://www.w3schools.com/tags/att_standard_id.asp
Additionally, these identifiers are case-sensitive. So I thought of using a hashing function like SHA or MD5, to hash the identifiers I get, then use them as ids for my spans, and I can apply the hashing function again to find my element.
This seems complicated for such a simple functionality. Is there a better way to do this? or maybe a very simple hashing function that would guarantee id
-friendly chars and case-sensitivity? (HTML's id
is not case-sensitive, that's another reason to consider hashing functions)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你能放弃你得到的标识符并只实现像这样的简单的东西:
Can you ditch the identifier you get and just implement something simple like this:
您可以只用一个数字和某种字符串来增加 id 以作为 ID 的开头。
跨度 ID 为“a1”、“a2”等。
You could just increment the id's with a number and some sort of string to begin the ID.
The span id's would be "a1", "a2" etc.
我猜问题是您认为稍后您将获得相同的字符串并希望以相同的方式转换它们,然后使用它们来查找原始的相应元素?
如果是这样,您只需要仔细消毒琴弦即可。一系列正则表达式可以帮助您将无效字符映射到有效字符,并使大写字母独一无二。例如,您可以将
"A"
转换为"-a-"
,将"+"
转换为"-plus-"
。精心选择的方案应该保证冲突的可能性(即有人给你一个看起来像另一个字符串的转义版本的字符串)应该非常小,并且在任何情况下都可以立即检测到。
I'm guessing that the problem is that you're thinking later you'll be getting the same strings and will want to transform them in the same way, and then use these to find the original corresponding elements?
If so, you'll just need to sanitize your strings carefully. A series of regular expressions could help you map from invalid to valid characters, and make the capitals unique. For instance, you could transform
"A"
into"-a-"
, and"+"
into"-plus-"
.A carefully chosen scheme should guarantee that the chances of a collision (i.e. someone giving you a string that looks like an escaped version of another string) should be very small, and in any case, detectable immediately.