简体   繁体   English

查找DOM元素的最佳实践

[英]Best practice in finding a DOM element

I want to toggle(hide/show) an element when a button is being pressed. 我想在按下按钮时切换(隐藏/显示)一个元素。 I have two ways as to implement this: 我有两种实现方法:

  1. Find the element according to its class name, eg $('.my-content') 根据元素的类名查找元素,例如$('.my-content')

  2. Find the element according to its relevant DOM position towards the button, eg $('#my-button').parent().next().next().next() 根据元素相对于按钮的相关DOM位置查找元素,例如$('#my-button').parent().next().next().next()

However, none of the above seems to me very reliable since in case someone changes the HTML code, the above approaches should not work. 但是,在我看来,上述任何方法都不是非常可靠的,因为如果有人更改了HTML代码,则上述方法将不起作用。 Is there something more reliable I am missing? 我还缺少更可靠的东西吗?

A very good practice is to decouple HTML, CSS and JS. 一个很好的做法是 HTML,CSS和JS 分离

When binding javascript to DOM elements you should use javascript selectors . 将javascript绑定到DOM元素时,应使用javascript选择器 Basically classes with some custom prefix (like js- ) which will be used only for javascript purposes (not css style). 基本上是带有一些自定义前缀(例如js- )的类,这些前缀仅用于javascript目的(而不是CSS样式)。

So whenever the DOM tree structure or the CSS class names are changed, you can still have your working JS selector 因此,无论何时更改DOM树结构或CSS类名称,您仍然可以使用工作的JS选择器

HTML HTML

<div class="my-content js-toggle-element"></div>

JS JS

$('.js-toggle-element')

CSS CSS

.my-content{ ... }

Plus, using Javascript Selectors: 另外,使用Javascript选择器:

  • makes HTML highly readable : you can easily find out what will happen to that element with that js class 使HTML更具可读性 :使用该js类,您可以轻松找出该元素将发生什么
  • allows you to easily apply/disapply that behaviour also to other elements in the future, simply by adding/removing that class in your HTML and without affecting CSS at all 允许您将来在其他元素中轻松应用/取消该行为,只需在HTML中添加/删除该类,而根本不影响CSS

     <div class="my-content js-toggle-element"></div> ... <div class="another-content-to-toggle js-toggle-element"></div> 
  1. If it's a specific element, supply it with an Id value and use that to find it. 如果是特定元素,请为其提供一个ID值,然后使用该值来查找它。
  2. If it's a TYPE of element, use a class name. 如果它是TYPE元素,请使用类名。

Other than that, there's no real conventions. 除此之外,没有真正的约定。 Just try and make sure that somebody reading your code understands what is going on. 只要尝试确保阅读您的代码的人了解发生了什么。

Using jQuery will be much easiest way. 使用jQuery将是最简单的方法。 Like this - 像这样 -

$( ".target" ).toggle();

The matched elements will be revealed or hidden immediately, with no animation, by changing the CSS display property. 通过更改CSS显示属性,匹配的元素将立即显示或隐藏,而不会产生动画。 If the element is initially displayed, it will be hidden; 如果最初显示该元素,则它将被隐藏; if hidden, it will be shown. 如果隐藏,它将显示。

Reference - jQuery Toggle 参考-jQuery Toggle

如果元素的类或元素在DOM中的位置正在更改,则可以尝试使用内部文本选择它

$("button:contains('buttontextgoeshere')")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM