问题描述
我注意到在监控/尝试回答常见的jQuery问题时,有一些使用javascript而不是jQuery的实践,它实际上使你能够写得更少并且做 ...同样的量。并且还可能产生性能优势。
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.
具体示例
$(this)
vs this
在引用点击的对象id的点击事件中
Inside a click event referencing the clicked objects id
jQuery
$(this).attr("id");
Javascript
Javascript
this.id;
还有其他常见做法吗?可以更轻松地完成某些Javascript操作,而无需将jQuery添加到组合中。或者这是一个罕见的情况? (实际上需要更多代码的jQuery快捷方式)
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)
with:
上面的措辞很差。 getAttribute
不是替代品,但它确实检索从服务器发送的属性的值,以及其对应的 setAttribute
会设置它。在某些情况下是必要的。
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.
以下句子覆盖了它。 以获得更好的治疗效果。
The sentences below sort of covered it. See this answer for a better treatment.
el.getAttribute('someName');
...以便直接访问属性。请注意,属性与属性不同(尽管它们有时会互相镜像)。当然还有 setAttribute
。
...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.
假设您遇到需要打开所有标签的页面的情况特定类型。使用jQuery简单易行:
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:
$('span').unwrap(); // unwrap all span elements
但是如果有很多,你可能想做一点原生DOM API:
But if there are many, you may want to do a little native 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] );
}
此代码非常简短,它的性能优于jQuery版本,并且可以很容易在你的个人图书馆中成为一个可重复使用的功能。
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.
看起来我有一个外部的无限循环,而
因为而(spans [0])
,但因为我们正在处理实时列表,所以当我们执行 parent.removeChild(跨度[0]); 。这是一个非常漂亮的功能,我们在使用Array(或类似Array的对象)时错过了这个功能。
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.
这篇关于何时使用Vanilla JavaScript与jQuery?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!