什么时候使用普通的JavaScript和jQuery?

时间:2022-04-10 22:36:05

I have noticed while monitoring/attempting to answer common jQuery questions, that there are certain practices using javascript, instead of jQuery, that actually enable you to write less and do ... well the same amount. And may also yield performance benefits.

在监视/尝试回答常见的jQuery问题时,我注意到有一些使用javascript而不是jQuery的实践可以让您编写更少的内容并完成……相同数量。也可能产生性能效益。

A specific example

一个具体的例子

$(this) vs this

$()vs

Inside a click event referencing the clicked objects id

在单击事件中引用单击的对象id。

jQuery

jQuery

$(this).attr("id");

Javascript

Javascript

this.id;

Are there any other common practices like this? Where certain Javascript operations could be accomplished easier, without bringing jQuery into the mix. Or is this a rare case? (of a jQuery "shortcut" actually requiring more code)

还有其他类似的常见做法吗?在这里,可以更容易地完成某些Javascript操作,而无需将jQuery混入其中。还是这种情况很罕见?(jQuery“快捷方式”实际上需要更多代码)

EDIT : While I appreciate the answers regarding jQuery vs. plain javascript performance, I am actually looking for much more quantitative answers. While using jQuery, instances where one would actually be better off (readability/compactness) to use plain javascript instead of using $(). In addition to the example I gave in my original question.

编辑:虽然我很欣赏关于jQuery和普通javascript性能的答案,但实际上我正在寻找更多的定量答案。在使用jQuery时,使用纯javascript而不是使用$()会更好(可读性/紧凑性)。除了我在最初的问题中给出的例子。

13 个解决方案

#1


200  

  • this.id (as you know)
  • 这一点。id(你知道)
  • this.value (on most input types. only issues I know are IE when a <select> doesn't have value properties set on its <option> elements, or radio inputs in Safari.)
  • 这一点。值(对于大多数输入类型)。我只知道当
  • this.className to get or set an entire "class" property
  • 这一点。获取或设置整个“类”属性的类名
  • this.selectedIndex against a <select> to get the selected index
  • 这一点。针对
  • this.options against a <select> to get a list of <option> elements
  • 这一点。对
  • this.text against an <option> to get its text content
  • 这一点。针对 <选项> 的文本获取其文本内容
  • this.rows against a <table> to get a collection of <tr> elements
  • 这一点。针对 的行获取 元素的集合
  • this.cells against a <tr> to get its cells (td & th)
  • 这一点。针对的细胞获取其细胞(td & th)
  • this.parentNode to get a direct parent
  • 这一点。获取直接父节点
  • this.checked to get the checked state of a checkbox Thanks @Tim Down
  • 这一点。检查以获取复选框的选中状态,谢谢@Tim
  • this.selected to get the selected state of an option Thanks @Tim Down
  • 这一点。选择一个选项来获得选择的状态,谢谢@Tim。
  • this.disabled to get the disabled state of an input Thanks @Tim Down
  • 这一点。禁用以获得输入的禁用状态,谢谢@Tim
  • this.readOnly to get the readOnly state of an input Thanks @Tim Down
  • 这一点。readOnly获得输入的readOnly状态,感谢@Tim
  • this.href against an <a> element to get its href
  • 这一点。针对元素的href获取其href
  • this.hostname against an <a> element to get the domain of its href
  • 这一点。针对元素的主机名获取其href的域
  • this.pathname against an <a> element to get the path of its href
  • 这一点。针对元素的路径名,以获取其href的路径
  • this.search against an <a> element to get the querystring of its href
  • 这一点。搜索元素以获取其href的查询字符串
  • this.src against an element where it is valid to have a src
  • 这一点。src针对元素,在元素中有src是有效的

...I think you get the idea.

…我想你懂的。

There will be times when performance is crucial. Like if you're performing something in a loop many times over, you may want to ditch jQuery.

有时,性能是至关重要的。就像如果你在循环中多次执行某件事情一样,你可能想要抛弃jQuery。

In general you can replace:

一般来说,你可以替换:

$(el).attr('someName');

with:

:

Above was poorly worded. getAttribute is not a replacement, but it does retrieve the value of an attribute sent from the server, and its corresponding setAttribute will set it. Necessary in some cases.

措辞不当。getAttribute不是一个替代品,但它会检索从服务器发送的属性的值,其相应的setAttribute会设置它。在某些情况下有必要。

The sentences below sort of covered it. See this answer for a better treatment.

下面的句子有点覆盖了它。请看这个答案来获得更好的治疗。

el.getAttribute('someName');

...in order to access an attribute directly. Note that attributes are not the same as properties (though they mirror each other sometimes). Of course there's setAttribute too.

…为了直接访问属性。注意,属性与属性并不相同(尽管它们有时相互镜像)。当然还有setAttribute。

Say you had a situation where received a page where you need to unwrap all tags of a certain type. It is short and easy with jQuery:

假设有这样一种情况:收到一个页面,需要打开某个类型的所有标记。jQuery简洁明了:

$('span').unwrap();  // unwrap all span elements

But if there are many, you may want to do a little native DOM API:

但是如果有很多,您可能需要做一些本地DOM API:

var spans = document.getElementsByTagName('span');

while( spans[0] ) {
    var parent = spans[0].parentNode;
    while( spans[0].firstChild ) {
        parent.insertBefore( spans[0].firstChild, spans[0]);
    }
    parent.removeChild( spans[0] );
}

This code is pretty short, it performs better than the jQuery version, and can easily be made into a reusable function in your personal library.

这段代码非常短,比jQuery版本性能更好,并且可以很容易地在您的个人库中创建可重用的函数。

It may seem like I have an infinite loop with the outer while because of while(spans[0]), but because we're dealing with a "live list" it gets updated when we do the parent.removeChild(span[0]);. This is a pretty nifty feature that we miss out on when working with an Array (or Array-like object) instead.

因为while(跨越[0]),看起来我与外部的循环是无限的,但是因为我们正在处理一个“活动列表”,所以当我们处理parent.removeChild(span[0])时,它会被更新。这是一个非常漂亮的特性,我们在使用数组(或类似数组的对象)时忽略了它。

#2


58  

The correct answer is that you'll always take a performance penalty when using jQuery instead of 'plain old' native JavaScript. That's because jQuery is a JavaScript Library. It is not some fancy new version of JavaScript.

正确的答案是,在使用jQuery而不是“普通旧的”本机JavaScript时,您总是要付出性能代价。这是因为jQuery是一个JavaScript库。这并不是什么新奇的JavaScript新版本。

The reason that jQuery is powerful is that it makes some things which are overly tedious in a cross-browser situation (AJAX is one of the best examples) and smooths over the inconsistencies between the myriad of available browsers and provides a consistent API. It also easily facilitates concepts like chaining, implied iteration, etc, to simplify working on groups of elements together.

jQuery强大的原因是它使一些东西在跨浏览器环境中过于单调乏味(AJAX是最好的例子之一),并消除了无数可用浏览器之间的不一致性,并提供了一致的API。它还可以方便地简化链接、隐含迭代等概念,从而简化对元素组的处理。

Learning jQuery is no substitute for learning JavaScript. You should have a firm basis in the latter so that you fully appreciate what knowing the former is making easier for you.

学习jQuery并不能替代学习JavaScript。你应该对后者有一个坚定的基础,这样你才会完全理解知道前者对你来说更容易。

-- Edited to encompass comments --

——编辑后包含评论—

As the comments are quick to point out (and I agree with 100%) the statements above refer to benchmarking code. A 'native' JavaScript solution (assuming it is well written) will outperform a jQuery solution that accomplishes the same thing in nearly every case (I'd love to see an example otherwise). jQuery does speed up development time, which is a significant benefit which I do not mean to downplay. It facilitates easy to read, easy to follow code, which is more than some developers are capable of creating on their own.

由于评论很快指出(我100%同意)上面的语句引用了基准代码。“原生”JavaScript解决方案(假设它写得很好)将胜过jQuery解决方案,几乎在所有情况下都实现相同的功能(我希望看到其他例子)。jQuery确实加快了开发时间,这是一个巨大的好处,我并不是有意淡化它。它易于阅读,易于遵循代码,这比一些开发人员能够自己创建的要多。

In my opinion then, the answer depends on what you're attempting to achieve. If, as I presumed based on your reference to performance benefits, you're after the best possible speed out of your application, then using jQuery introduces overhead every time you call $(). If you're going for readability, consistency, cross browser compatibility, etc, then there are certainly reasons to favor jQuery over 'native' JavaScript.

在我看来,答案取决于你想要达到的目标。如果根据您对性能好处的引用,假设您的应用程序的速度是最好的,那么使用jQuery每次调用$()时都会引入开销。如果您想要可读性、一致性、跨浏览器兼容性等,那么肯定有理由选择jQuery而不是“本机”JavaScript。

#3


35  

There's a framework called... oh guess what? Vanilla JS. Hope you get the joke... :D It sacrifices code legibility for performance... Comparing it to jQuery bellow you can see that retrieving a DOM element by ID is almost 35X faster. :)

有一个框架,叫做……哦,你猜怎么着?香草JS。希望你能听懂这个笑话……:它牺牲了代码的易读性。将它与jQuery bellow进行比较,您可以看到通过ID检索DOM元素的速度几乎快了35倍。:)

So if you want performance you'd better try Vanilla JS and draw your own conclusions. Maybe you won't experience JavaScript hanging the browser's GUI/locking up the UI thread during intensive code like inside a for loop.

所以如果你想要表现,你最好试试Vanilla JS,并得出你自己的结论。在密集的代码中,比如在for循环中,您可能不会体验到JavaScript挂起浏览器的GUI/锁定UI线程。

Vanilla JS is a fast, lightweight, cross-platform framework for building incredible, powerful JavaScript applications.

Vanilla JS是一个快速、轻量级、跨平台的框架,用于构建难以置信的、强大的JavaScript应用程序。

On their homepage there's some perf comparisons:

在他们的主页上有一些比较:

什么时候使用普通的JavaScript和jQuery?

#4


17  

There's already an accepted answer but I believe no answer typed directly here can be comprehensive in its list of native javascript methods/attributes that has practically guaranteed cross-browser support. For that may I redirect you to quirksmode:

已经有了一个公认的答案,但是我认为在这里没有直接输入的答案可以在它的本地javascript方法/属性列表中得到全面的支持,这些方法实际上保证了跨浏览器的支持。为此,我可以把你转到屈克斯默德:

http://www.quirksmode.org/compatibility.html

http://www.quirksmode.org/compatibility.html

It is perhaps the most comprehensive list of what works and what doesn't work on what browser anywhere. Pay particular attention to the DOM section. It is a lot to read but the point is not to read it all but to use it as a reference.

它可能是最全面的列表,列出了在任何浏览器上都可以工作的和不能工作的。要特别注意DOM部分。要读的东西很多,但重点不是全部都读,而是把它作为参考。

When I started seriously writing web apps I printed out all the DOM tables and hung them on the wall so that I know at a glance what is safe to use and what requires hacks. These days I just google something like quirksmode parentNode compatibility when I have doubts.

当我开始认真地编写web应用程序时,我打印出了所有的DOM表,并将它们挂在墙上,这样我就能一眼看出什么是安全的,什么是需要破解的。这些天,当我有疑问的时候,我就像奇克斯莫德父母节点兼容性一样。

Like anything else, judgement is mostly a matter of experience. I wouldn't really recommend you to read the entire site and memorize all the issues to figure out when to use jQuery and when to use plain JS. Just be aware of the list. It's easy enough to search. With time you will develop an instinct of when plain JS is preferable.

和其他事情一样,判断主要是经验的问题。我不建议您阅读整个站点并记住所有问题,以确定何时使用jQuery,何时使用普通JS。只要注意列表。搜索起来很容易。随着时间的推移,你会产生一种直觉,认为普通的JS更可取。


PS: PPK (the author of the site) also has a very nice book that I do recommend reading

附注:PPK(网站的作者)也有一本很不错的书,我推荐你去读

#5


14  

When:

当:

  1. you know that there is unflinching cross-browser support for what you are doing, and
  2. 您知道,对于您正在做的事情,您可以毫不畏惧的跨浏览器支持。
  3. it is not significantly more code to type, and
  4. 它没有明显更多的代码类型,而且。
  5. it is not significantly less readable, and
  6. 它没有明显的可读性,而且。
  7. you are reasonably confident that jQuery will not choose different implementations based on the browser to achieve better performance, then:
  8. 您有理由相信,jQuery不会根据浏览器选择不同的实现来获得更好的性能,那么:

use JavaScript. Otherwise use jQuery (if you can).

使用JavaScript。否则使用jQuery(如果可以的话)。

Edit: This answer applies both when choosing to use jQuery overall versus leaving it out, as well as choosing whether to to use vanilla JS inside jQuery. Choosing between attr('id') and .id leans in favor of JS, while choosing between removeClass('foo') versus .className = .className.replace( new Regexp("(?:^|\\s+)"+foo+"(?:\\s+|$)",'g'), '' ) leans in favor of jQuery.

编辑:这个答案既适用于选择使用jQuery,也适用于选择是否在jQuery中使用普通的JS。在attr('id')和.id之间进行选择时,倾向于JS,而在removeClass('foo')和. classname = . classname之间进行选择。替换(新Regexp(“(?:^ | \ \ s +)”+ foo +”(?:\ \ s + | $)”,“g”),”)倾向于支持jQuery。

#6


13  

Others' answers have focused on the broad question of "jQuery vs. plain JS." Judging from your OP, I think you were simply wondering when it's better to use vanilla JS if you've already chosen to use jQuery. Your example is a perfect example of when you should use vanilla JS:

其他人的回答集中在“jQuery vs plain JS”这个宽泛的问题上。从您的OP中判断,我认为您只是在想,如果您已经选择使用jQuery,那么最好使用香草JS。你的例子是一个很好的例子,说明你应该使用香草JS:

$(this).attr('id');

(美元).attr(“id”);

Is both slower and (in my opinion) less readable than:

的速度和(在我看来)的可读性都不如:

this.id.

this.id。

It's slower because you have to spin up a new JS object just to retrieve the attribute the jQuery way. Now, if you're going to be using $(this) to perform other operations, then by all means, store that jQuery object in a variable and operate with that. However, I've run into many situations where I just need an attribute from the element (like id or src).

它比较慢,因为您必须旋转一个新的JS对象,以便以jQuery的方式检索属性。现在,如果要使用$(this)执行其他操作,那么务必将jQuery对象存储在一个变量中,并使用它进行操作。但是,在许多情况下,我只需要从元素(比如id或src)中获得一个属性。

Are there any other common practices like this? Where certain Javascript operations could be accomplished easier, without bringing jQuery into the mix. Or is this a rare case? (of a jQuery "shortcut" actually requiring more code)

还有其他类似的常见做法吗?在这里,可以更容易地完成某些Javascript操作,而无需将jQuery混入其中。还是这种情况很罕见?(jQuery“快捷方式”实际上需要更多代码)

I think the most common case is the one you describe in your post; people wrapping $(this) in a jQuery object unnecessarily. I see this most often with id and value (instead using $(this).val()).

我认为最常见的情况是你在文章中描述的;人们不必要地将$(this)包装在jQuery对象中。我经常在id和value(而不是使用$(this).val())中看到这一点。

Edit: Here's an article that explains why using jQuery in the attr() case is slower. Confession: stole it from the tag wiki, but I think it's worth mentioning for the question.

编辑:这里有一篇文章解释为什么在attr()案例中使用jQuery比较慢。自白:从维基上偷的,但我觉得这个问题值得一提。

Edit again: Given the readability/performance implications of just accessing attributes directly, I'd say a good rule of thumb is probably to try to to use this.<attributename> when possible. There are probably some instances where this won't work because of browser inconsistencies, but it's probably better to try this first and fall back on jQuery if it doesn't work.

再次编辑:考虑到直接访问属性的可读性/性能影响,我认为一个很好的经验法则是尝试使用它。< attributename >如果可能的话。在某些情况下,由于浏览器的不一致性,这可能无法工作,但是如果不能工作,最好先尝试一下jQuery。

#7


9  

If you are mostly concerned about performance, your main example hits the nail on the head. Invoking jQuery unnecessarily or redundantly is, IMHO, the second main cause of slow performance (the first being poor DOM traversal).

如果您最关心的是性能,那么您的主要示例就击中了要害。不必要地或冗余地调用jQuery是慢性能的第二个主要原因(第一个是糟糕的DOM遍历)。

It's not really an example of what you're looking for, but I see this so often that it bears mentioning: One of the best ways to speed up performance of your jQuery scripts is to cache jQuery objects, and/or use chaining:

这并不是您要寻找的真正示例,但我经常看到这一点,因此值得一提:加快jQuery脚本性能的最佳方法之一是缓存jQuery对象,并/或使用链接:

// poor
$(this).animate({'opacity':'0'}, function() { $(this).remove(); });

// excellent
var element = $(this);
element.animate({'opacity':'0'}, function() { element.remove(); });

// poor
$('.something').load('url');
$('.something').show();

// excellent
var something = $('#container').children('p.something');
something.load('url').show();

#8


6  

I've found there is certainly overlap between JS and JQ. The code you've shown is a good example of that. Frankly, the best reason to use JQ over JS is simply browser compatibility. I always lean toward JQ, even if I can accomplish something in JS.

我发现JS和JQ之间确实存在重叠。您所展示的代码就是一个很好的例子。坦率地说,使用JQ而不使用JS的最佳理由仅仅是浏览器兼容性。我总是倾向于JQ,即使我能用JS完成一些事情。

#9


5  

This is my personal view, but as jQuery is JavaScript anyway, I think theoretically it cannot perform better than vanilla JS ever.

这是我的个人观点,但由于jQuery是JavaScript,我认为理论上它的性能不会比普通的JS更好。

But practically it may perform better than hand-written JS, as one's hand-written code may be not as efficient as jQuery.

但实际上,它的性能可能比手工编写的JS要好,因为手工编写的代码可能不如jQuery有效。

Bottom-line - for smaller stuff I tend to use vanilla JS, for JS intensive projects I like to use jQuery and not reinvent the wheel - it's also more productive.

底线——对于更小的东西,我倾向于使用普通的JS,对于JS密集型的项目,我喜欢使用jQuery,而不是重新发明*——它也更高效。

#10


3  

The first answer's live properties list of this as a DOM element is quite complete.

第一个答案的作为DOM元素的活动属性列表非常完整。

You may find also interesting to know some others.

你可能也会发现认识一些人很有趣。

When this is the document :

当这是文件:

  • this.forms to get an HTMLCollection of the current document forms,
  • 这一点。表单获取当前文档表单的HTMLCollection,
  • this.anchors to get an HTMLCollection of all the HTMLAnchorElements with name being set,
  • 这一点。锚获取所有已设置名称的HTMLAnchorElements的HTMLCollection,
  • this.links to get an HTMLCollection of all the HTMLAnchorElements with href being set,
  • 这一点。获取所有htmlanchorelement的html集合,并设置href的链接,
  • this.images to get an HTMLCollection of all the HTMLImageElements
  • 这一点。获取所有HTMLImageElements的HTMLCollection的图像
  • and the same with the deprecated applets as this.applets
  • 对于已弃用的applet,也可以使用this.applet

When you work with document.forms, document.forms[formNameOrId] gets the so named or identified form.

当你使用文档时。表单、文档。表单[formNameOrId]获取如此命名或识别的表单。

When this is a form :

当这是一个表格:

  • this[inputNameOrId] to get the so named or identified field
  • 这个[inputNameOrId]获取如此命名或标识的字段

When this is form field:

当这是表单字段时:

  • this.type to get the field type
  • 这一点。类型以获取字段类型

When learning jQuery selectors, we often skip learning already existing HTML elements properties, which are so fast to access.

在学习jQuery选择器时,我们经常跳过学习已经存在的HTML元素属性,这些属性的访问速度非常快。

#11


1  

$(this) is different to this :

$(这个)与这个不同:

By using $(this) you are ensuring the jQuery prototype is being passed onto the object.

通过使用$(this),您可以确保将jQuery原型传递到对象上。

#12


1  

As usual I'm coming late to this party.

和往常一样,我参加这个聚会迟到了。

It wasn't the extra functionality that made me decide to use jQuery, as attractive as that was. After all nothing stops you from writing your own functions.

并不是额外的功能让我决定使用jQuery,就像它那样吸引人。毕竟,没有什么能阻止你编写自己的函数。

It was the fact that there were so many tricks to learn when modifying the DOM to avoid memory leaks (I'm talking about you IE). To have one central resource that managed all those sort of issues for me, written by people who were a whole lot better JS coders than I ever will be, that was being continually reviewed, revised and tested was god send.

在修改DOM以避免内存泄漏(我说的是IE)时,有很多技巧需要学习。有一个为我管理所有这些问题的中心资源,由那些比我更好的JS程序员写的,那是上帝的旨意。

I guess this sort of falls under the cross browser support/abstraction argument.

我猜这属于跨浏览器支持/抽象的论点。

And of course jQuery does not preclude the use of straight JS when you needed it. I always felt the two seemed to work seamlessly together.

当然,jQuery并不排除在需要的时候使用直JS。我总觉得这两个人好像天衣无缝地在一起工作。

Of course if your browser is not supported by jQuery or you are supporting a low end environment (older phone?) then a large .js file might be a problem. Remember when jQuery used to be tiny?

当然,如果您的浏览器不受jQuery支持,或者您支持低端环境(旧的电话?),那么一个大的.js文件可能是一个问题。还记得jQuery什么时候还很小吗?

But normally the performance difference is not an issue of concern. It only has to be fast enough. With Gigahertz of CPU cycles going to waste every second, I'm more concerned with the performance of my coders, the only development resources that doesn't double in power every 18 months.

但通常情况下,性能差异并不令人担忧。它只需要足够快。随着CPU周期的千兆赫每秒钟都在浪费,我更关心的是我的程序员的性能,这是唯一的开发资源,每18个月的电量不会翻一番。

That said I'm currently looking into accessibility issues and apparently .innerHTML is a bit of a no no with that. jQuery of course depends on .innerHTML, so now I'm looking for a framework that will depend on the somewhat tedious methods that are allowed. And I can imagine such a framework will run slower than jQuery, but as long as it performs well enough, I'll be happy.

这就是说,我目前正在研究可访问性问题,显然,innerhtml有点不一样。jQuery当然依赖于。innerhtml,所以现在我正在寻找一个框架,它将依赖于允许的有点乏味的方法。我可以想象这样一个框架会比jQuery运行得慢,但是只要它运行得足够好,我就会很高兴。

#13


1  

Here's a non-technical answer - many jobs may not allow certain libraries, such as jQuery.

这里有一个非技术的答案——许多作业可能不允许某些库,比如jQuery。

In fact, In fact, Google doesn't allow jQuery in any of their code (nor React, because it's owned by Facebook), which you might not have known until the interviewer says "Sorry, but you cant use jQuery, it's not on the approved list at XYZ Corporation". Vanilla JavaScript works absolutely everywhere, every time, and will never give you this problem. If you rely on a library yes you get speed and ease, but you lose universality.

实际上,谷歌不允许jQuery进入他们的任何代码(也不允许使用jQuery,因为它属于Facebook),在面试官说“对不起,你不能使用jQuery,它不在XYZ公司的批准列表中”之前,你可能并不知道。Vanilla JavaScript在任何地方都能工作,每次都不会给你这个问题。如果你依赖于一个库,你会得到速度和舒适度,但是你会失去通用性。

Also, speaking of interviewing, the other downside is that if you say you need to use a library to solve a JavaScript problem during a code quiz, it comes across like you don't actually understand the problem, which looks kinda bad. Whereas if you solve it in raw vanilla JavaScript it demonstrates that you actually understand and can solve every part of whatever problem they throw in front of you.

另外,谈到面试,另一个缺点是如果你说你需要在代码测试中使用一个库来解决一个JavaScript问题,它会让你觉得你实际上不理解这个问题,这看起来很糟糕。然而,如果你用原始的JavaScript来解决它,它表明你确实理解并能解决他们面前的任何问题。

#1


200  

  • this.id (as you know)
  • 这一点。id(你知道)
  • this.value (on most input types. only issues I know are IE when a <select> doesn't have value properties set on its <option> elements, or radio inputs in Safari.)
  • 这一点。值(对于大多数输入类型)。我只知道当
  • this.className to get or set an entire "class" property
  • 这一点。获取或设置整个“类”属性的类名
  • this.selectedIndex against a <select> to get the selected index
  • 这一点。针对
  • this.options against a <select> to get a list of <option> elements
  • 这一点。对
  • this.text against an <option> to get its text content
  • 这一点。针对 <选项> 的文本获取其文本内容
  • this.rows against a <table> to get a collection of <tr> elements
  • 这一点。针对 的行获取 元素的集合
  • this.cells against a <tr> to get its cells (td & th)
  • 这一点。针对的细胞获取其细胞(td & th)
  • this.parentNode to get a direct parent
  • 这一点。获取直接父节点
  • this.checked to get the checked state of a checkbox Thanks @Tim Down
  • 这一点。检查以获取复选框的选中状态,谢谢@Tim
  • this.selected to get the selected state of an option Thanks @Tim Down
  • 这一点。选择一个选项来获得选择的状态,谢谢@Tim。
  • this.disabled to get the disabled state of an input Thanks @Tim Down
  • 这一点。禁用以获得输入的禁用状态,谢谢@Tim
  • this.readOnly to get the readOnly state of an input Thanks @Tim Down
  • 这一点。readOnly获得输入的readOnly状态,感谢@Tim
  • this.href against an <a> element to get its href
  • 这一点。针对元素的href获取其href
  • this.hostname against an <a> element to get the domain of its href
  • 这一点。针对元素的主机名获取其href的域
  • this.pathname against an <a> element to get the path of its href
  • 这一点。针对元素的路径名,以获取其href的路径
  • this.search against an <a> element to get the querystring of its href
  • 这一点。搜索元素以获取其href的查询字符串
  • this.src against an element where it is valid to have a src
  • 这一点。src针对元素,在元素中有src是有效的

...I think you get the idea.

…我想你懂的。

There will be times when performance is crucial. Like if you're performing something in a loop many times over, you may want to ditch jQuery.

有时,性能是至关重要的。就像如果你在循环中多次执行某件事情一样,你可能想要抛弃jQuery。

In general you can replace:

一般来说,你可以替换:

$(el).attr('someName');

with:

:

Above was poorly worded. getAttribute is not a replacement, but it does retrieve the value of an attribute sent from the server, and its corresponding setAttribute will set it. Necessary in some cases.

措辞不当。getAttribute不是一个替代品,但它会检索从服务器发送的属性的值,其相应的setAttribute会设置它。在某些情况下有必要。

The sentences below sort of covered it. See this answer for a better treatment.

下面的句子有点覆盖了它。请看这个答案来获得更好的治疗。

el.getAttribute('someName');

...in order to access an attribute directly. Note that attributes are not the same as properties (though they mirror each other sometimes). Of course there's setAttribute too.

…为了直接访问属性。注意,属性与属性并不相同(尽管它们有时相互镜像)。当然还有setAttribute。

Say you had a situation where received a page where you need to unwrap all tags of a certain type. It is short and easy with jQuery:

假设有这样一种情况:收到一个页面,需要打开某个类型的所有标记。jQuery简洁明了:

$('span').unwrap();  // unwrap all span elements

But if there are many, you may want to do a little native DOM API:

但是如果有很多,您可能需要做一些本地DOM API:

var spans = document.getElementsByTagName('span');

while( spans[0] ) {
    var parent = spans[0].parentNode;
    while( spans[0].firstChild ) {
        parent.insertBefore( spans[0].firstChild, spans[0]);
    }
    parent.removeChild( spans[0] );
}

This code is pretty short, it performs better than the jQuery version, and can easily be made into a reusable function in your personal library.

这段代码非常短,比jQuery版本性能更好,并且可以很容易地在您的个人库中创建可重用的函数。

It may seem like I have an infinite loop with the outer while because of while(spans[0]), but because we're dealing with a "live list" it gets updated when we do the parent.removeChild(span[0]);. This is a pretty nifty feature that we miss out on when working with an Array (or Array-like object) instead.

因为while(跨越[0]),看起来我与外部的循环是无限的,但是因为我们正在处理一个“活动列表”,所以当我们处理parent.removeChild(span[0])时,它会被更新。这是一个非常漂亮的特性,我们在使用数组(或类似数组的对象)时忽略了它。

#2


58  

The correct answer is that you'll always take a performance penalty when using jQuery instead of 'plain old' native JavaScript. That's because jQuery is a JavaScript Library. It is not some fancy new version of JavaScript.

正确的答案是,在使用jQuery而不是“普通旧的”本机JavaScript时,您总是要付出性能代价。这是因为jQuery是一个JavaScript库。这并不是什么新奇的JavaScript新版本。

The reason that jQuery is powerful is that it makes some things which are overly tedious in a cross-browser situation (AJAX is one of the best examples) and smooths over the inconsistencies between the myriad of available browsers and provides a consistent API. It also easily facilitates concepts like chaining, implied iteration, etc, to simplify working on groups of elements together.

jQuery强大的原因是它使一些东西在跨浏览器环境中过于单调乏味(AJAX是最好的例子之一),并消除了无数可用浏览器之间的不一致性,并提供了一致的API。它还可以方便地简化链接、隐含迭代等概念,从而简化对元素组的处理。

Learning jQuery is no substitute for learning JavaScript. You should have a firm basis in the latter so that you fully appreciate what knowing the former is making easier for you.

学习jQuery并不能替代学习JavaScript。你应该对后者有一个坚定的基础,这样你才会完全理解知道前者对你来说更容易。

-- Edited to encompass comments --

——编辑后包含评论—

As the comments are quick to point out (and I agree with 100%) the statements above refer to benchmarking code. A 'native' JavaScript solution (assuming it is well written) will outperform a jQuery solution that accomplishes the same thing in nearly every case (I'd love to see an example otherwise). jQuery does speed up development time, which is a significant benefit which I do not mean to downplay. It facilitates easy to read, easy to follow code, which is more than some developers are capable of creating on their own.

由于评论很快指出(我100%同意)上面的语句引用了基准代码。“原生”JavaScript解决方案(假设它写得很好)将胜过jQuery解决方案,几乎在所有情况下都实现相同的功能(我希望看到其他例子)。jQuery确实加快了开发时间,这是一个巨大的好处,我并不是有意淡化它。它易于阅读,易于遵循代码,这比一些开发人员能够自己创建的要多。

In my opinion then, the answer depends on what you're attempting to achieve. If, as I presumed based on your reference to performance benefits, you're after the best possible speed out of your application, then using jQuery introduces overhead every time you call $(). If you're going for readability, consistency, cross browser compatibility, etc, then there are certainly reasons to favor jQuery over 'native' JavaScript.

在我看来,答案取决于你想要达到的目标。如果根据您对性能好处的引用,假设您的应用程序的速度是最好的,那么使用jQuery每次调用$()时都会引入开销。如果您想要可读性、一致性、跨浏览器兼容性等,那么肯定有理由选择jQuery而不是“本机”JavaScript。

#3


35  

There's a framework called... oh guess what? Vanilla JS. Hope you get the joke... :D It sacrifices code legibility for performance... Comparing it to jQuery bellow you can see that retrieving a DOM element by ID is almost 35X faster. :)

有一个框架,叫做……哦,你猜怎么着?香草JS。希望你能听懂这个笑话……:它牺牲了代码的易读性。将它与jQuery bellow进行比较,您可以看到通过ID检索DOM元素的速度几乎快了35倍。:)

So if you want performance you'd better try Vanilla JS and draw your own conclusions. Maybe you won't experience JavaScript hanging the browser's GUI/locking up the UI thread during intensive code like inside a for loop.

所以如果你想要表现,你最好试试Vanilla JS,并得出你自己的结论。在密集的代码中,比如在for循环中,您可能不会体验到JavaScript挂起浏览器的GUI/锁定UI线程。

Vanilla JS is a fast, lightweight, cross-platform framework for building incredible, powerful JavaScript applications.

Vanilla JS是一个快速、轻量级、跨平台的框架,用于构建难以置信的、强大的JavaScript应用程序。

On their homepage there's some perf comparisons:

在他们的主页上有一些比较:

什么时候使用普通的JavaScript和jQuery?

#4


17  

There's already an accepted answer but I believe no answer typed directly here can be comprehensive in its list of native javascript methods/attributes that has practically guaranteed cross-browser support. For that may I redirect you to quirksmode:

已经有了一个公认的答案,但是我认为在这里没有直接输入的答案可以在它的本地javascript方法/属性列表中得到全面的支持,这些方法实际上保证了跨浏览器的支持。为此,我可以把你转到屈克斯默德:

http://www.quirksmode.org/compatibility.html

http://www.quirksmode.org/compatibility.html

It is perhaps the most comprehensive list of what works and what doesn't work on what browser anywhere. Pay particular attention to the DOM section. It is a lot to read but the point is not to read it all but to use it as a reference.

它可能是最全面的列表,列出了在任何浏览器上都可以工作的和不能工作的。要特别注意DOM部分。要读的东西很多,但重点不是全部都读,而是把它作为参考。

When I started seriously writing web apps I printed out all the DOM tables and hung them on the wall so that I know at a glance what is safe to use and what requires hacks. These days I just google something like quirksmode parentNode compatibility when I have doubts.

当我开始认真地编写web应用程序时,我打印出了所有的DOM表,并将它们挂在墙上,这样我就能一眼看出什么是安全的,什么是需要破解的。这些天,当我有疑问的时候,我就像奇克斯莫德父母节点兼容性一样。

Like anything else, judgement is mostly a matter of experience. I wouldn't really recommend you to read the entire site and memorize all the issues to figure out when to use jQuery and when to use plain JS. Just be aware of the list. It's easy enough to search. With time you will develop an instinct of when plain JS is preferable.

和其他事情一样,判断主要是经验的问题。我不建议您阅读整个站点并记住所有问题,以确定何时使用jQuery,何时使用普通JS。只要注意列表。搜索起来很容易。随着时间的推移,你会产生一种直觉,认为普通的JS更可取。


PS: PPK (the author of the site) also has a very nice book that I do recommend reading

附注:PPK(网站的作者)也有一本很不错的书,我推荐你去读

#5


14  

When:

当:

  1. you know that there is unflinching cross-browser support for what you are doing, and
  2. 您知道,对于您正在做的事情,您可以毫不畏惧的跨浏览器支持。
  3. it is not significantly more code to type, and
  4. 它没有明显更多的代码类型,而且。
  5. it is not significantly less readable, and
  6. 它没有明显的可读性,而且。
  7. you are reasonably confident that jQuery will not choose different implementations based on the browser to achieve better performance, then:
  8. 您有理由相信,jQuery不会根据浏览器选择不同的实现来获得更好的性能,那么:

use JavaScript. Otherwise use jQuery (if you can).

使用JavaScript。否则使用jQuery(如果可以的话)。

Edit: This answer applies both when choosing to use jQuery overall versus leaving it out, as well as choosing whether to to use vanilla JS inside jQuery. Choosing between attr('id') and .id leans in favor of JS, while choosing between removeClass('foo') versus .className = .className.replace( new Regexp("(?:^|\\s+)"+foo+"(?:\\s+|$)",'g'), '' ) leans in favor of jQuery.

编辑:这个答案既适用于选择使用jQuery,也适用于选择是否在jQuery中使用普通的JS。在attr('id')和.id之间进行选择时,倾向于JS,而在removeClass('foo')和. classname = . classname之间进行选择。替换(新Regexp(“(?:^ | \ \ s +)”+ foo +”(?:\ \ s + | $)”,“g”),”)倾向于支持jQuery。

#6


13  

Others' answers have focused on the broad question of "jQuery vs. plain JS." Judging from your OP, I think you were simply wondering when it's better to use vanilla JS if you've already chosen to use jQuery. Your example is a perfect example of when you should use vanilla JS:

其他人的回答集中在“jQuery vs plain JS”这个宽泛的问题上。从您的OP中判断,我认为您只是在想,如果您已经选择使用jQuery,那么最好使用香草JS。你的例子是一个很好的例子,说明你应该使用香草JS:

$(this).attr('id');

(美元).attr(“id”);

Is both slower and (in my opinion) less readable than:

的速度和(在我看来)的可读性都不如:

this.id.

this.id。

It's slower because you have to spin up a new JS object just to retrieve the attribute the jQuery way. Now, if you're going to be using $(this) to perform other operations, then by all means, store that jQuery object in a variable and operate with that. However, I've run into many situations where I just need an attribute from the element (like id or src).

它比较慢,因为您必须旋转一个新的JS对象,以便以jQuery的方式检索属性。现在,如果要使用$(this)执行其他操作,那么务必将jQuery对象存储在一个变量中,并使用它进行操作。但是,在许多情况下,我只需要从元素(比如id或src)中获得一个属性。

Are there any other common practices like this? Where certain Javascript operations could be accomplished easier, without bringing jQuery into the mix. Or is this a rare case? (of a jQuery "shortcut" actually requiring more code)

还有其他类似的常见做法吗?在这里,可以更容易地完成某些Javascript操作,而无需将jQuery混入其中。还是这种情况很罕见?(jQuery“快捷方式”实际上需要更多代码)

I think the most common case is the one you describe in your post; people wrapping $(this) in a jQuery object unnecessarily. I see this most often with id and value (instead using $(this).val()).

我认为最常见的情况是你在文章中描述的;人们不必要地将$(this)包装在jQuery对象中。我经常在id和value(而不是使用$(this).val())中看到这一点。

Edit: Here's an article that explains why using jQuery in the attr() case is slower. Confession: stole it from the tag wiki, but I think it's worth mentioning for the question.

编辑:这里有一篇文章解释为什么在attr()案例中使用jQuery比较慢。自白:从维基上偷的,但我觉得这个问题值得一提。

Edit again: Given the readability/performance implications of just accessing attributes directly, I'd say a good rule of thumb is probably to try to to use this.<attributename> when possible. There are probably some instances where this won't work because of browser inconsistencies, but it's probably better to try this first and fall back on jQuery if it doesn't work.

再次编辑:考虑到直接访问属性的可读性/性能影响,我认为一个很好的经验法则是尝试使用它。< attributename >如果可能的话。在某些情况下,由于浏览器的不一致性,这可能无法工作,但是如果不能工作,最好先尝试一下jQuery。

#7


9  

If you are mostly concerned about performance, your main example hits the nail on the head. Invoking jQuery unnecessarily or redundantly is, IMHO, the second main cause of slow performance (the first being poor DOM traversal).

如果您最关心的是性能,那么您的主要示例就击中了要害。不必要地或冗余地调用jQuery是慢性能的第二个主要原因(第一个是糟糕的DOM遍历)。

It's not really an example of what you're looking for, but I see this so often that it bears mentioning: One of the best ways to speed up performance of your jQuery scripts is to cache jQuery objects, and/or use chaining:

这并不是您要寻找的真正示例,但我经常看到这一点,因此值得一提:加快jQuery脚本性能的最佳方法之一是缓存jQuery对象,并/或使用链接:

// poor
$(this).animate({'opacity':'0'}, function() { $(this).remove(); });

// excellent
var element = $(this);
element.animate({'opacity':'0'}, function() { element.remove(); });

// poor
$('.something').load('url');
$('.something').show();

// excellent
var something = $('#container').children('p.something');
something.load('url').show();

#8


6  

I've found there is certainly overlap between JS and JQ. The code you've shown is a good example of that. Frankly, the best reason to use JQ over JS is simply browser compatibility. I always lean toward JQ, even if I can accomplish something in JS.

我发现JS和JQ之间确实存在重叠。您所展示的代码就是一个很好的例子。坦率地说,使用JQ而不使用JS的最佳理由仅仅是浏览器兼容性。我总是倾向于JQ,即使我能用JS完成一些事情。

#9


5  

This is my personal view, but as jQuery is JavaScript anyway, I think theoretically it cannot perform better than vanilla JS ever.

这是我的个人观点,但由于jQuery是JavaScript,我认为理论上它的性能不会比普通的JS更好。

But practically it may perform better than hand-written JS, as one's hand-written code may be not as efficient as jQuery.

但实际上,它的性能可能比手工编写的JS要好,因为手工编写的代码可能不如jQuery有效。

Bottom-line - for smaller stuff I tend to use vanilla JS, for JS intensive projects I like to use jQuery and not reinvent the wheel - it's also more productive.

底线——对于更小的东西,我倾向于使用普通的JS,对于JS密集型的项目,我喜欢使用jQuery,而不是重新发明*——它也更高效。

#10


3  

The first answer's live properties list of this as a DOM element is quite complete.

第一个答案的作为DOM元素的活动属性列表非常完整。

You may find also interesting to know some others.

你可能也会发现认识一些人很有趣。

When this is the document :

当这是文件:

  • this.forms to get an HTMLCollection of the current document forms,
  • 这一点。表单获取当前文档表单的HTMLCollection,
  • this.anchors to get an HTMLCollection of all the HTMLAnchorElements with name being set,
  • 这一点。锚获取所有已设置名称的HTMLAnchorElements的HTMLCollection,
  • this.links to get an HTMLCollection of all the HTMLAnchorElements with href being set,
  • 这一点。获取所有htmlanchorelement的html集合,并设置href的链接,
  • this.images to get an HTMLCollection of all the HTMLImageElements
  • 这一点。获取所有HTMLImageElements的HTMLCollection的图像
  • and the same with the deprecated applets as this.applets
  • 对于已弃用的applet,也可以使用this.applet

When you work with document.forms, document.forms[formNameOrId] gets the so named or identified form.

当你使用文档时。表单、文档。表单[formNameOrId]获取如此命名或识别的表单。

When this is a form :

当这是一个表格:

  • this[inputNameOrId] to get the so named or identified field
  • 这个[inputNameOrId]获取如此命名或标识的字段

When this is form field:

当这是表单字段时:

  • this.type to get the field type
  • 这一点。类型以获取字段类型

When learning jQuery selectors, we often skip learning already existing HTML elements properties, which are so fast to access.

在学习jQuery选择器时,我们经常跳过学习已经存在的HTML元素属性,这些属性的访问速度非常快。

#11


1  

$(this) is different to this :

$(这个)与这个不同:

By using $(this) you are ensuring the jQuery prototype is being passed onto the object.

通过使用$(this),您可以确保将jQuery原型传递到对象上。

#12


1  

As usual I'm coming late to this party.

和往常一样,我参加这个聚会迟到了。

It wasn't the extra functionality that made me decide to use jQuery, as attractive as that was. After all nothing stops you from writing your own functions.

并不是额外的功能让我决定使用jQuery,就像它那样吸引人。毕竟,没有什么能阻止你编写自己的函数。

It was the fact that there were so many tricks to learn when modifying the DOM to avoid memory leaks (I'm talking about you IE). To have one central resource that managed all those sort of issues for me, written by people who were a whole lot better JS coders than I ever will be, that was being continually reviewed, revised and tested was god send.

在修改DOM以避免内存泄漏(我说的是IE)时,有很多技巧需要学习。有一个为我管理所有这些问题的中心资源,由那些比我更好的JS程序员写的,那是上帝的旨意。

I guess this sort of falls under the cross browser support/abstraction argument.

我猜这属于跨浏览器支持/抽象的论点。

And of course jQuery does not preclude the use of straight JS when you needed it. I always felt the two seemed to work seamlessly together.

当然,jQuery并不排除在需要的时候使用直JS。我总觉得这两个人好像天衣无缝地在一起工作。

Of course if your browser is not supported by jQuery or you are supporting a low end environment (older phone?) then a large .js file might be a problem. Remember when jQuery used to be tiny?

当然,如果您的浏览器不受jQuery支持,或者您支持低端环境(旧的电话?),那么一个大的.js文件可能是一个问题。还记得jQuery什么时候还很小吗?

But normally the performance difference is not an issue of concern. It only has to be fast enough. With Gigahertz of CPU cycles going to waste every second, I'm more concerned with the performance of my coders, the only development resources that doesn't double in power every 18 months.

但通常情况下,性能差异并不令人担忧。它只需要足够快。随着CPU周期的千兆赫每秒钟都在浪费,我更关心的是我的程序员的性能,这是唯一的开发资源,每18个月的电量不会翻一番。

That said I'm currently looking into accessibility issues and apparently .innerHTML is a bit of a no no with that. jQuery of course depends on .innerHTML, so now I'm looking for a framework that will depend on the somewhat tedious methods that are allowed. And I can imagine such a framework will run slower than jQuery, but as long as it performs well enough, I'll be happy.

这就是说,我目前正在研究可访问性问题,显然,innerhtml有点不一样。jQuery当然依赖于。innerhtml,所以现在我正在寻找一个框架,它将依赖于允许的有点乏味的方法。我可以想象这样一个框架会比jQuery运行得慢,但是只要它运行得足够好,我就会很高兴。

#13


1  

Here's a non-technical answer - many jobs may not allow certain libraries, such as jQuery.

这里有一个非技术的答案——许多作业可能不允许某些库,比如jQuery。

In fact, In fact, Google doesn't allow jQuery in any of their code (nor React, because it's owned by Facebook), which you might not have known until the interviewer says "Sorry, but you cant use jQuery, it's not on the approved list at XYZ Corporation". Vanilla JavaScript works absolutely everywhere, every time, and will never give you this problem. If you rely on a library yes you get speed and ease, but you lose universality.

实际上,谷歌不允许jQuery进入他们的任何代码(也不允许使用jQuery,因为它属于Facebook),在面试官说“对不起,你不能使用jQuery,它不在XYZ公司的批准列表中”之前,你可能并不知道。Vanilla JavaScript在任何地方都能工作,每次都不会给你这个问题。如果你依赖于一个库,你会得到速度和舒适度,但是你会失去通用性。

Also, speaking of interviewing, the other downside is that if you say you need to use a library to solve a JavaScript problem during a code quiz, it comes across like you don't actually understand the problem, which looks kinda bad. Whereas if you solve it in raw vanilla JavaScript it demonstrates that you actually understand and can solve every part of whatever problem they throw in front of you.

另外,谈到面试,另一个缺点是如果你说你需要在代码测试中使用一个库来解决一个JavaScript问题,它会让你觉得你实际上不理解这个问题,这看起来很糟糕。然而,如果你用原始的JavaScript来解决它,它表明你确实理解并能解决他们面前的任何问题。