jQuery(反)模式:使用字符串操作构建选择器
我经常发现自己使用字符串操作(拆分、搜索、替换、连接、+、连接)来构建选择器。
好还是坏?
Too often I find myself building selectors with string manipulation (split, search, replace, concat, +, join).
Good or bad?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这有什么问题吗?有什么替代方案——只是将它们硬编码为单个字符串?但是您可以在网站上使用约定来组织布局。如果您只是在一个地方定义选择器组件,并使用它来构建选择器,听起来这比遍历所有代码并在它出现的任何地方进行搜索替换要麻烦得多。
我想说,假设您以其他方式组织字符串(在一个地方定义,在多个地方使用),这是很好的。
What's wrong with that? What are the alternatives — just hardcoding them as single strings? But you may use conventions on your site for how the layout is organized. If you just define the selector components in one place, and use it to build a selector, sounds like this would be less hassle than going through all the code and doing search-replace everywhere it shows up.
I'd say it's good assuming you have the strings otherwise organized (defined in one place, used in several places).
这与您的问题有些无关,但是:
我建议的一件事是谨慎对待基于后代的选择器或子选择器(例如:'div.product > span.price')。通常,UI 部分会被重新组织、移动或用其他东西包裹。当这种情况发生时,基于后代的选择器就会崩溃。
另一件需要记住的事情是,基于属性的选择器(例如:'input[value="Login"]')在处理本地化内容(如果属性值已本地化)时通常很脆弱。
This is somewhat unrelated to your question, but:
One thing I would recommend is to be cautious with descendant-based or child selectors (e.g.: 'div.product > span.price'). Often, UI parts are being reorganized, moved around or wrapped with something else. When it happens, descendant-based selectors break.
Another thing to keep in mind is that attribute-based selectors (e.g.: 'input[value="Login"]') are often fragile when dealing with localized content (if attribute values are localized).