javascript - 将 document.querySelector 或 document.querySelectorAll 的结果转换为 jquery 对象,反之亦然,无需重新选择?
问题描述
我试图减少 jQuery 的使用,但有时我仍然需要在 jQuery 中使用方法。
是否可以将返回document.querySelector
或document.querySelectorAll
转换为 jQuery 对象,或将 jQuery 选择转换为 document.querySelector() 或 document.querySelectorAll() 将返回的 Element 或 NodeList 对象?
重新进行选择似乎比使用我已经拥有的更昂贵。
这是一个例子document.querySelector
:
let qsOutput = document.querySelector('#my_id');
//now if I want to use jQuery's .attr (just as an example)
qsOutput.attr("alt", "the new alt attribute"); //.attr() is a jquery function
我该怎么做?我是否只需要再次选择并浪费原始捕获的资源?
我不是在问如何更改 vanilla JavaScript 中的属性,我正在尝试减少 jQuery 的使用,但仍需要不时使用它,但是当我已经通过它进行新选择时document.querySelector
,似乎浪费。如果可能的话,我想重用它的返回document.querySelector
并将其“升级”到 jQuery。
解决方案
您可以将一个或多个元素传递给 jQuery 函数。
$(qsOutput).attr("alt", "the new alt attribute");
推荐阅读
- c# - 如何在 Azure 中处理 API 和客户端之间的身份验证
- java - Java泛型的统一参数传递和类型安全
- image-processing - 需要使用圆霍夫变换检测图像中的最大圆
- r - 有没有办法从 coxme 模型中获得事件概率?
- swift - 为 ObservableObject ViewModels 编写单元测试并发布结果
- c++ - 使用 popen 定时运行程序
- sympy - 带有非符号的 Sympy 导数
- c# - 如何修复字符串不断返回null c#
- hibernate - Spring Boot + Hibernate + JPA = 使用存储库的命名 oracle 过程调用失败
- ios - Xcode 将 Objective-C、Objective-C++ 项目导入 Swift 项目