如何避免在使用jQuery创建丰富的客户端体验时锁定我的HTML结构? [英] How to avoid locking my HTML structure when using jQuery to create rich client experiences?

查看:73
本文介绍了如何避免在使用jQuery创建丰富的客户端体验时锁定我的HTML结构?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在我已经遇到了三次,我觉得是时候我学会了如何避免这种情况。



通常,我构建了HTML。一旦我满足于结构和视觉设计,我开始使用jQuery来连接事件和其他的东西。



有时,客户端需要一个小的更改或即使是一个中等的变化,需要我更改HTML,这导致我的JavaScript代码中断,因为它取决于不再存在的HTML选择器。



我如何避免每次创建一个网站时,都要自己挖进这个洞?任何文章我应该阅读?

解决方案

使您的选择器不那么脆弱。




  • 不要通过索引,下一个兄弟姐妹,直接的孩子等使用选择器

  • 使用类,即使您必须更改标签名称和元素在HTML中的位置,选择器仍然可以工作

  • 不要使用parent()或child()而不指定一个选择器。确保你寻找一个具有特定类的父母或孩子



有时候,根据返工的数量,你必须更新脚本。保持尽可能分离,但总是有一些耦合,它是脚本和HTML之间的接口。这就像能够更改实现而不必更改接口。有时您需要新的行为需要一个新界面。



我认为帮助您的最佳方法是让您在HTML中显示一个小的变更示例改变你的jQuery代码。然后,我们可以向您展示如何在更新HTML


时最小化对JS的更改

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 structure and visual design, I start using jQuery to wire up events and other things.

Thing is, sometimes the client wants a small change or even a medium change that requires me to change the HTML, and this causes my javascript code to break because it depends on HTML selectors that no longer exist.

How can I avoid digging myself into this hole every time I create a website? Any articles I should read?

解决方案

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

这篇关于如何避免在使用jQuery创建丰富的客户端体验时锁定我的HTML结构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆