使用 JQuery 隐藏 DOM 元素而无需多次调用 .hide() 的最佳方法
因此,一旦用户点击查看交易本身,我的网站就会使用 Google 地图 API 来显示托管交易的公司的地图。如果地图函数返回 true,我将使用 $('#map').show()
来显示它。
我知道当用户单击页面上的另一个按钮来隐藏 div 时我可以使用 .hide() ,但是页面上有大约 7 个按钮可以执行不同的操作并使用 $('#map') 。每个中的 hide()
都是可行的,但似乎是重复且丑陋的编码。
当用户单击“查看交易”按钮之外的任何其他按钮(可能是某种形式的 .each()
)时,是否有人有任何关于隐藏 div 的建议?
So my site uses the Google Maps API to display a map of the company hosting the deal once the user clicks to view the deal itself. If the map function returns true I user $('#map').show()
to display it.
I know I can use the .hide() when the user clicks another button on the page to hide the div, but I have about 7 buttons on the page that do different things and using $('#map').hide()
in each one is doable but seems repetitive and ugly coding wise.
Does anyone have any suggestions as to hide the div when a user clicks on any other button besides the 'view deal' button, maybe some form of .each()
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我希望您的按钮共享相同的CSS:
I'm hoping your buttons share the same CSS:
您可以为所有按钮设置一个处理程序,仅管理地图可见性,然后为更具体的内容设置其他处理程序:
You could have a handler for all buttons, that manages just the map visibility, and then other handlers for the more specific stuff:
您可以使用切换而不是显示按钮:
如果正在显示,它将隐藏,如果隐藏,它将显示。
you can use toggle instead of show button:
if it is being shown it will hide, and if it is hidden it will be shown.
创建一个 javascript 函数来处理设置视图。让每个按钮通过传入它们想要的视图来调用该函数。然后,您只需在代码中的一处(在该函数中)即可为新视图准备页面。这使得您的所有代码比为每个按钮使用完全独立的代码更加干燥。
由于某些原因,jQuery 事件处理程序(声明匿名函数)常见的设计模式往往使人们认为他们必须在每个事件处理程序中单独编写代码,而不是从执行大部分或全部操作的事件处理程序中调用共享函数。只需一处即可操作所有按钮。
Make a single javascript function that handles setting your view. Have each button call that function by just passing in the view they want. Then, in only one place in your code (in that function), you can handle preparing the page for the new view. This allows all your code to by much more DRY than having completely separate code for each button.
For some reason, the design pattern common with jQuery event handlers (declaring anonymous functions) tends to make people think they have to have separately written code in each event handler rather than calling a shared function from the event handler that does most or all of the work for all your buttons in just one place.