jQuery (anti-)pattern: building selectors with string manipulation

房东的猫 提交于 2019-12-22 08:15:40

问题


Too often I find myself building selectors with string manipulation (split, search, replace, concat, +, join).

Good or bad?


回答1:


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).




回答2:


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).



来源:https://stackoverflow.com/questions/1567496/jquery-anti-pattern-building-selectors-with-string-manipulation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!