[英]What is the vanilla JS equivalent of jQuery's $(document)?
我试图找出以下代码的vanilla等价物:
$(document).attr('key', 'value');
document
- 它不是一个元素,所以你不能在它上面调用setAttribute
document.documentElement
- 返回html
标记。 这与jquery所针对的“元素”不同 $(document)[0]
似乎在Chrome Inspector中返回一个阴影元素 $(document).attr('key', 'somethingUnique')
是jQuery创建它自己的阴影元素模拟文档,所以它可以像真正的元素一样对待它吗? 当你执行$(document)
时,jQuery实际引用了什么元素?
jQuery结果集是一个类似于对象的数组,通常包含DOMElement
,但jQuery并不真正关心结果集中对象的类型。 无论是DOMElements
还是存储在jQuery结果集中的任何其他元素都是以某种方式进行模拟/包装,它们都直接存储在结果集中。 jQuery试图通过查看它们的可用函数来弄清楚它对这些对象的作用。
当你调用.attr
,jQuery会检查集合中的每个对象,如果它具有函数getAttribute
如果是这种情况,则假定它还具有函数setAttribute
。
如果它没有函数getAttribute
,那么它会将函数调用转发给.prop()
函数,而prop将在内部执行:
elem[name] = value
因此,如果将普通对象传递给jQuery,那么它只会设置其属性。
var a = { } $(a).attr('test', 'hello world'); console.dir(a) // for `a` the property `test` is set
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
如果你将getAttribute
和setAttribute
函数添加到该对象,那么jQuery将调用这些:
var a = { getAttribute() { }, setAttribute() { console.log('setAttribute was called') } } $(a).attr('test', 'hello world'); console.dir(a);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
但是,您应该始终假设,jQuery执行这些测试的方式和顺序可能会发生变化。 而且,如果在文档中明确提到它,则只依赖它。
我相信你对$(document)
没有提及document
是不正确的,因此,答案是(非常简单):
document['key'] = 'value'
例如在Chrome中:
> $(document)[0] === document
true
> $(document).attr('blarg', 'narf')
n.fn.init [document, context: document]
> document.blarg
"narf"
> document.foo = 'bar'
"bar"
> document.foo
"bar"
jQuery只是直接将值赋给document
。
$(document).attr('test', 'hello world');
console.log(document['test']); // prints "hello world"
我真的认为jQuery会包装DOM元素,因为出于某种原因,我从来没有写过var x = $('#x')
以便稍后重用它,但回想起$。
这就是我写的原因:
是的它被包裹了
但在阅读@ t.niese 回答后 ,我试过了
var x = $('#x')
var y = $('#y')
var ref = x[0]
x[0] = y[0] // hack jQuery Object reference to DOM element
setTimeout(() => x.html('1'), 1000) // actually writes in #y
setTimeout(() => x.html('2'), 2000) // actually writes in #y
setTimeout(() => { x.push(ref) }, 2500) // hack jQuery Object reference to DOM element
setTimeout(() => x.html('3'), 3000) // actually writes in both #x and #y
并且理解我不写var x = $('#x')
不是因为它是一个包装对象,而是因为它不是一个包装对象。
我认为API的入口点是$
,但我可能会看到像var api = $()
的API,以及入口点为(el) => api.push(el)
或(sel) => api.push(document.querySelector(sel))
我可以$().push
但我不能$().forEach
也不移动也不移位但是删除索引,也是
在示例中
setTimeout(() => { x.map((item) => {console.log(item)}) }, 3500)
记录0和1,而不是元素。 使用jQuery版本3.3.1进行测试
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.