本文介绍了什么时候使用 Vanilla JavaScript 和 jQuery?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在监控/尝试回答常见的 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

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)

以上措辞不当.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.

由于 while(spans[0]) 的原因,我似乎对外部 while 进行了无限循环,但是因为我们正在处理实时list" 当我们执行 parent.removeChild(span[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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 20:56