javascript选择器_如何通过选择正确JavaScript选择器来避免沮丧
javascript选择器
选择器如何影响代码的快速指南 (A quick guide on how selectors affect your code)
While working on a project, I ran into an issue in my code. I was attempting to define multiple HTML elements into a collection and then change those elements based on some preset conditions. I struggled for roughly four hours of coding time (across two days) debugging my code and trying to figure out why I wasn’t getting my desired outcome.
在处理项目时,我的代码遇到了一个问题。 我试图将多个HTML元素定义到一个集合中,然后根据一些预设条件更改这些元素。 我花了大约四个小时的时间(大约两天)来调试我的代码,并试图弄清为什么没有得到理想的结果,这让我很费力。
Turns out I had used document.querySelectorAll() to assign my elements to a variable, and then I was attempting to change those elements. The only problem is that particular JavaScript selector returns a static node list. Since it isn’t a live representation of the elements, I wasn’t able to change them later in my code.
原来,我曾使用document.querySelectorAll()将元素分配给变量,然后尝试更改这些元素。 唯一的问题是特定JavaScript选择器返回静态节点列表 。 由于它不是元素的实时表示,因此以后我无法在代码中对其进行更改。
假设条件 (Assumptions)
In this article, I assume a few things to be true:
在本文中,我假设有几件事情是正确的:
- You are working in “plain or vanilla” JavaScript (no framework / library)您正在使用“普通的或原始的” JavaScript(没有框架/库)
- You have a basic understanding of JavaScript elements / selectors您对JavaScript元素/选择器有基本的了解
- You have a basic understanding of the DOM您对DOM有基本的了解
坚韧不拔 (The Nitty-gritty)
In the event I have assumed too much, I have provided links to relevant material within the article that I hope will be helpful.
如果我承担过多,我提供了文章中相关材料的链接,希望对您有所帮助。
JavaScript is such a vast and rich ecosystem that it’s no surprise that there are many ways of accomplishing the same task. Depending on your task, the way it is accomplished matters to a certain degree.
JavaScript是一个如此庞大而丰富的生态系统,以多种方式完成同一任务也就不足为奇了。 根据您的任务,完成的方式在一定程度上很重要。
You can dig a hole with your hands, but it’s much easier and more efficient to do it with a shovel.
您可以用手挖一个洞,但是用铲子挖起来要容易得多,效率也更高。
To that end, I hope to “hand you a shovel” after you’ve read this article.
为此,我希望在阅读本文后为您“铲”。
为工作选择合适的工具 (Choosing the right tool for the job)
I’ve had the question, “Which element selector should I use?” several times. Until now, I haven’t had much desire or need to learn the difference as long as my code produced the desired result. After all, what does the color of the taxi matter as long as it gets you to your destination safely and in a timely manner…right?
我有一个问题,“我应该使用哪个元素选择器?” 几次。 到目前为止,只要我的代码产生了期望的结果,我就没有太多的愿望或需要学习区别。 毕竟,只要它能安全,及时地到达目的地,出租车的颜色有什么关系?对吗?
Let’s start with some of the ways to select DOM elements in JavaScript. There are more ways (I believe) to select elements, but the ones listed here are by far the most prevalent I’ve come across.
让我们从在JavaScript中选择DOM元素的一些方法开始。 (我相信)有更多选择元素的方法,但是到目前为止,这里列出的方法是我遇到的最普遍的方法。
document.getElementById() (document.getElementById())
These will only ever return one (1) element because, by their nature, ID’s are unique and there can only be one (with the same name) on the page at a time.
它们只会返回一(1)个元素,因为从本质上讲,ID是唯一的,并且一次在页面上只能有一个(同名)。
It returns an object that matches the string passed into it. It returns null if no matching ID is found in your HTML.
它返回与传递给它的字符串匹配的对象。 如果在HTML中找不到匹配的ID,则返回null 。
Syntax example -> document.getElementById(‘main_content’)
语法示例-&g t; document.getElementById('main_conten t')
Unlike some selectors that we’ll get to later in the article, there is no need for a # to denote element id.
与我们将在本文后面介绍的一些选择器不同,不需要使用#来表示元素ID。
document.getElementsByTagName() (document.getElementsByTagName())
Notice the “S” in elements — this selector returns multiples in an array-like structure known as an HTML collection — all of the document is searched including the root node (the document object) for a matching name. This element selector starts at the top of the document and continues down, searching for tags that match the passed-in string.
注意元素中的“ S”-此选择器返回倍数 呈阵列状结构 称为HTML集合 -搜索所有文档,包括根节点 (文档对象)以找到匹配的名称。 此元素选择器从文档顶部开始,一直向下,搜索与传入字符串匹配的标签。
If you are looking to use native array methods you’re out of luck. That is, unless you convert the returned results into an array to iterate over them, or use the ES6 spread operator — both of which are beyond the scope of this article. But I wanted you to know it is possible to use array methods if you wish to.
如果您希望使用本机数组方法,那么您会很不幸。 也就是说,除非您将返回的结果转换为数组以对其进行迭代,或者使用ES6 传播运算符 -二者均不在本文的讨论范围之内。 但是我想让您知道是否可以使用数组方法。
Syntax example -> document.getElementsByTagName(‘header_links’). This selector also accepts p, div, body, or any other valid HTML tag.
语法示例-&g t; document.getElementsByTagName('header_li nks')。 此选择器还接受p,div,body或任何其他有效HTML标记。
document.getElementsByClassName() (document.getElementsByClassName())
Class name selector — again notice the “S” in elements — this selector returns multiples in an array-like structure known as an HTML collection of class names. It matches the passed-in string (can take multiple class names, although they are separated by a space), searches all of the document, can be called on any element, and only returns descendants of the passed in class.
类名选择器-再次注意元素中的“ S”-此选择器返回倍数 呈阵列状结构 被称为类名称的HTML集合 。 它与传入的字符串匹配(可以用多个类名,尽管它们之间用空格隔开),搜索所有文档,可以在任何元素上调用,并且仅返回传入类的后代。
Also, no . (period) is needed to denote class name
另外,没有。 需要(句号)来表示班级名称
Syntax example: document.getElementsByClassName(‘className’)
语法示例: document.getElementsByClassName('classNam e')
document.querySelector() (document.querySelector())
This selector will only ever return one (1) element.
此选择器将仅返回一(1)个元素。
Only the first element matching the passed-in string will be returned. If no matches for the provided string are found, null is returned.
仅返回与传入字符串匹配的第一个元素。 如果找不到与提供的字符串匹配的字符串,则为null 返回。
Syntax example: document.querySelector(‘#side_note’) or document.querySelector(‘.header_links’)
语法示例: document.querySelector('#side_note ') 或document.querySelector('。header_link s')
Unlike all of our previous examples, this selector requires a . (period) to denote class or an # (octothorp) to denote an ID and works with all CSS selectors.
与我们之前的所有示例不同,此选择器需要一个。 (句号)表示类,或# (octothorp)表示ID,并与所有CSS选择器一起使用。
document.querySelectorAll() (document.querySelectorAll())
This selector returns multiples that match the passed-in string and arranges them into another array like structure known as a node list.
该选择器返回与传入的字符串匹配的倍数 ,并将它们排列到另一个数组中,如结构称为节点列表 。
As with some of the previous examples, the node list cannot make use of native array methods like .forEach(). So if you want to use those, you must first convert the node list into an array. If you do not wish to convert, you can still iterate over the node list with a for…in statement.
与前面的一些示例一样,节点列表不能使用诸如.forEach( )之类的本机数组方法 。 因此,如果要使用它们,则必须首先将节点列表转换为数组。 如果您不希望进行转换,则仍然可以使用af 或…in语句遍历节点列表。
The passed in string must match a valid CSS selector — id, class names, types, attributes, values of attributes, etc.
传入的字符串必须与有效CSS选择器匹配-ID,类名,类型,属性,属性值等。
Syntax example: document.querySelectorAll(‘.footer_links’)
语法示例: document.querySelectorAll('。footer_link s')
结语 (Wrapping up)
By choosing the right selector for your coding needs, you’ll avoid many of the pitfalls I’ve fallen into. It can be incredibly frustrating when your code doesn’t work, but by ensuring that your selector matches your situational needs, you’ll have no trouble “digging with your shovel” :)
通过选择适合您的编码需求的选择器,可以避免我遇到的许多陷阱。 当您的代码不起作用时,它可能会令人难以置信的令人沮丧,但是通过确保您的选择器满足您的情况需求,您将“用铲子挖矿”毫无问题:)
Thank you for reading through this post. If you enjoyed it, please consider donating some claps to help others find it as well. I publish (actively managing my schedule to write more) related content on my blog. I’m also active on Twitter and am always happy to connect with other developers!
感谢您阅读这篇文章。 如果您喜欢它,请考虑捐赠一些拍手以帮助其他人找到它。 我在博客上发布(积极管理我的日程安排以写更多)相关内容。 我也在Twitter上很活跃,很高兴与其他开发人员联系!
翻译自: https://www.freecodecamp.org/news/how-to-avoid-frustration-by-choosing-the-right-javascript-selector-73c64c3906b6/
javascript选择器
相关文章:

Asp.net中GridView使用详解(引)【转】
Asp.net中GridView使用详解(引) GridView无代码分页排序 GridView选中,编辑,取消,删除 GridView正反双向排序 GridView和下拉菜单DropDownList结合 GridView和CheckBox结合 鼠标移到GridView某一行时改变该行的背景色方法一 鼠标移到GridView…

《任正非:我若贪生怕死,何来让你们英勇奋斗》
非常高兴尼泊尔代表处的进步,你们的一个历史项目概算亏损,从大前年亏损2.7亿美金,到前年亏损3000万美金,到去年盈利2140万美金。在喜马拉雅南麓一路爬坡,辛苦了。听说去年你们都涨了工资,我十分高兴。巴西代…

个人使用微信支付
微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 首先在PAYJS申请到商户号和密钥, 然后实现源码如下: <!DOCTYPE html> <html lang"zh"><head><meta charset"UTF-8"><title>…

构建node.js基础镜像_我如何使用Node.js构建工作抓取网络应用
构建node.js基础镜像by Oyetoke Tobi Emmanuel由Oyetoke Tobi Emmanuel 我如何使用Node.js构建工作抓取网络应用 (How I built a job scraping web app using Node.js) Scraping jobs from the web has now become easier thanks to Indreed.现在,借助Indreed&…

Robotium测试报告的生成方法(上)
7.1 使用junit-report生成报告 这个是参考网上的:http://www.xuebuyuan.com/2148574.html,经我个人验证是可行的方法,网上写的挺详细的,不过有些不太清楚明白的地方,鉴于网上说的有点迷茫,所以下面我再细化…

Python之向日志输出中添加上下文信息
除了传递给日志记录函数的参数(如msg)外,有时候我们还想在日志输出中包含一些额外的上下文信息。比如,在一个网络应用中,可能希望在日志中记录客户端的特定信息,如:远程客户端的IP地址和用户名。…

小程序点击图片自动播放视频,停止上一个视频播放
微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 通过列表的点击事件自动播放列表对应的视频,同时停止上一个视频的播放 源码: <view><view classvv wx:for{{vedio_data}} wx:key><view classblock stylemargin…

hitchhiker部署_Hitchhiker的React Router v4指南:无限远的递归路径!
hitchhiker部署Welcome to the third part of the Hitchhiker’s Guide to React Router v4. In this article we’re going to focus on recursive paths. If you’ve missed the first two parts, you can find part 1 here and part 2 here.欢迎阅读《 Hitchhiker React Rou…

smbpasswd 和 pdbedit 的区别
smbpasswd 和 pdbedit 的区别 以前我们在windows上共享文件的话,只需右击要共享的文件夹然后选择共享相关的选项设置即可。然而如何实现windows和linux的文件共享呢?这就涉及到了samba服务了,这个软件配置起来也不难,使用也非常简…

DB天气app冲刺二阶段第十一天(完结)
今天最后一天冲刺了,明天就不再冲刺了。。已经把所有的技术的问题还有设计的问题都弄好了吧应该说 至少目前来说是的。因为有的实现不了的或者需要耗费时间的已经果断舍弃了,然后需要完善的也都基本完善了。 现在还需要做的就是素材的收集整理。需要抽半…

如何超越console.log并充分利用浏览器的调试控制台
by Gilad Dayagi通过吉拉德达亚吉 The console object is a very useful feature of browsers that has been around for many years. It provides access to the browser’s debugging console.Most web developers know how to print messages to the console using console…

区域设置 ID (LCID) 表, 及获取方法
区域设置 ID (LCID) 表, 及获取方法 中国的区域设置 ID 是 2052, 如果经常打开微软软件的安装目录应该经常见到.获取很简单, 有现成的 API 函数: GetThreadLocale.beginShowMessage(IntToStr(GetThreadLocale)); //2052 end; 区域设置 ID (LCID) 表区域设置描述简写十六进制值十…

E201700525-hm
skeleton n. 骨骼; (建筑物等的) 骨架; 梗概; 骨瘦如柴的人(或动物);adj. 骨骼的; 骨瘦如柴的; 概略的; 基本的; cloud n. 云; 云状物; invoke vt. 乞灵,祈求; 提出或授引…以支持或证明; 召鬼; 借助;render …

php不显示报错
微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 error_reporting(E_ALL & ~E_NOTICE);

致谢 开源开发者的贡献_对开源做出的贡献如何使我成为更好的开发人员,以及如何做到这一点...
致谢 开源开发者的贡献by Luciano Strika通过卢西亚诺斯特里卡(Luciano Strika) 对开源做出的贡献如何使我成为更好的开发人员,以及如何做到这一点 (How contributing to open source made me a better developer — and how you can do it, too) So you’ve been …

欲精一行,必先通十行
将前端开发和服务器端开发做一个比较,前端开发没有服务器端开发“深”,服务器端开发没有前端开发“广”。经常听到做前端的同行抱怨需要学的东西太 多,东学一点西学一点,什么都会,但也什么都不精。很直接的结果就是沦为…

LeetCode 228: Summary Ranges
Given a sorted integer array without duplicates, return the summary of its ranges. For example, given [0,1,2,4,5,7], return ["0->2","4->5","7"]. 代码要求对数组中的元素进行分段。 首先给出字符串格式化函数,假设be…

JQ+ajax 提交表单不跳转页面
微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 代码 <div class"apply_box"><h1>合作申请</h1><div class"apply_l"><input type"text" maxlength"20" id"name" name&q…

node.js是开源的吗_为开源做贡献并不难:我为Node.js项目做贡献的旅程
node.js是开源的吗As a developer, you should consider contributing to open source software. Many of your potential employers will look favorably on these contributions.作为开发人员,您应该考虑为开源软件做贡献。 您的许多潜在雇主将对这些供款看好。 …

超级简单的jquery轮播图demo
<!DOCTYPE html> <html><head><meta charset"UTF-8"><title>轮播图demo</title><script type"text/javascript" src"js/jquery-3.2.1.slim.js" ></script><link rel"stylesheet" …

Mysql 操作技巧
复制表结构 表数据Mysql> create tables t2 like t1;Mysql> insert into t2 select * from t1; mysql 索引a、Alert Table 用来创建普通索引、Unique 唯一索引 (当前列数值不可重复) 或 Primary Key 主键索引Mysql> alter table table_name add index index_name(col…

JS实现复制到剪切板效果
微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 代码: <!DOCTYPE html> <html lang"en"><head><meta http-equiv"Content-Type" content"text/html; charsetutf-8" /><meta cha…

如何管理多个Python版本和虚拟环境
Addition January 2019: If you are coming back to this blog after upgrading to macOS Mojave please see this github issue for a solution to the common pyenv ‘zlib not available’ problem.此外,2019年1月:如果在升级到macOS Mojave之后又回到…

linux 下byte,char,unsigned char的区别
在linux中,对byte的定义为无符号char,而char默认为有符号char。 #ifndef BYTE #define BYTE unsigned char #endif以下ZZ百度知道: 在C中,默认的基础数据类型均为signed,现在我们以char为例,说明(signed) c…

词法作用域和动态作用域
JavaScript采用的是词法作用域 1.词法作用域 即函数定义时,即确定的作用域。js中的作用域链,在函数声明时候,就已经确定了,无论函数在何处调用,其作用域变量的查找都是按照定义是包含关系去查找。 2.动态作用域 变量的…

10-18 JS基础复习笔记
微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 1.JS类型 Numbel String Boolean Symbol Null Undefined Object(Funtion,Array,Data,Regexp); 2.字符串转数字类型 "122" //122 var a 1 2; console.log(a) //3 3.null 和 u…

vue.js crud_如何使用VS Code和ADO.NET使用ASP.NET Core执行CRUD操作
vue.js crud介绍 (Introduction) In this article we are going to create a web application using ASP.NET Core MVC with the help of Visual Studio Code and ADO.NET. We will be creating a sample Employee Record Management System and performing CRUD operations on…
redis事物命令示例
命令示例: 1. 事务被正常执行:#在Shell命令行下执行Redis的客户端工具。/> redis-cli#在当前连接上启动一个新的事务。redis 127.0.0.1:6379>multiOK#执行事务中的第一条命令,从该命令的返回结果可以看出,该命令并没有立即执…

JS 函数 函数递归
微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 重要:函数也是对象,你可以给它们添加属性或者更改它们的属性。 函数内部对象:arguments 解析:函数实际上是访问了函数体中一个名为 arguments 的内部对象…

swift设置启动图不现实_如何通过装饰房屋来开始在Swift中使用增强现实
swift设置启动图不现实by Ranadhir Dey由Ranadhir Dey 如何通过装饰房屋来开始在Swift中使用增强现实 (How to get started with augmented reality in Swift by decorating your home) If you’ve read my previous post, you already have a beautiful AR floor in your din…