javascript - 有没有办法像JQuery中的链接方法一样高效地表达Javascript代码?

标签 javascript jquery

在 jQuery 中,我们可以在一条语句中运行多个方法,以便高效地表达 jQuery 代码:

$("#p1").css("color", "red").html("Hello world!").attr("class","democlass");

Javascript 怎么样?

document.getElementById("p1").style.color = "red";
document.getElementById("p1").innerHTML = "Hello world!";
document.getElementById("p1").setAttribute("class","democlass");

最佳答案

性能提升只是因为您只搜索元素一次,然后将其存储在变量中。 jQuery 通过重复将该变量返回给您来使此操作变得简单,但是无论有或没有 jQuery,您都可以使用显式变量来达到相同的效果。

没有 jQuery:

var p1 = document.getElementById("p1");
p1.style.color = "red";
p1.innerHTML = "Hello world!";
p1.setAttribute("class","democlass");

使用 jQuery:

var p1 = $("#p1");
p1.css("color", "red");
p1.html("Hello world!");
p1.attr("class","democlass");

关于javascript - 有没有办法像JQuery中的链接方法一样高效地表达Javascript代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42293698/

相关文章:

javascript - 为可放置事件添加延迟

javascript - 我可以从绝对 URL 加载网络 worker 脚本吗?

Javascript:未终止的字符串文字

javascript - 在angular.js中,不带()的函数调用和带()的调用有区别吗?

javascript - 如何从匹配特定值的 MongoDB 文档更新数组?

jquery - 在字符串中查找文本并添加到其他位置

javascript - 如何使用 jquery 获取表中的祖 parent 文本

javascript - 这样做的目的是什么? (function ($) {//这里是函数代码 })(jQuery);

jquery - 使用 .slideToggle() (或任何其他 jQuery 方法)如何让一个 div 在单击按钮后与另一个重叠?

javascript - 使用 Extendscript 在 InDesign 中放置文件时指定编码