How to avoid locking my HTML structure when using jQuery to create rich client experiences?

前端 未结 1 1799
Happy的楠姐
Happy的楠姐 2020-12-21 23:08

I\'ve had this happen to me three times now and I feel it\'s time I learned how to avoid this scenario.

Typically, I build the HTML. Once I\'m content with the struc

1条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-21 23:28

    Make your selectors less brittle.

    • Don't use a selector by index, next sibling, immediate child, or the like
    • Use classes so even if you have to change the tag name and the element's position in the HTML, the selector will still work
    • Don't use parent() or child() without specifying a selector. Make sure you look for a parent or child with a specific class

    Sometimes, depending on the amount of rework, you'll have to update the script. Keep them as decoupled as possible, but there's always some coupling, it's the interface between script and HTML. It's like being able to change an implementation without having to change the interface. Sometimes you need new behavior that needs a new interface.

    I think the best way to help you is for you to show a small sample of a change in the HTML that required a change to your jQuery code. We could then show you how to minimize changes to JS as you update the HTML

    0 讨论(0)
提交回复
热议问题