CTS*_*_AE 23 javascript jquery
我试图找出以下代码的vanilla等价物:
$(document).attr('key', 'value');
Run Code Online (Sandbox Code Playgroud)
document- 它不是一个元素,所以你不能打电话setAttribute给它document.documentElement- 返回html标签.这与jquery所针对的"元素"不同$(document)[0] 似乎在Chrome Inspector中返回了一个阴影元素$(document).attr('key', 'somethingUnique') Chrome Inspector中不存在是jQuery创建它自己的阴影元素模拟文档,所以它可以像真正的元素一样对待它吗?你做$(document)什么时jQuery实际引用了什么元素?
t.n*_*ese 27
jQuery结果集是一个像对象一样的数组DOMElement,但是jQuery并不真正关心结果集中对象的类型.DOMElements在jQuery结果集中存储的任何其他元素都不会以某种方式被模拟/包装,它们直接存储在结果集中.jQuery试图通过查看它们的可用函数来弄清楚它对这些对象的作用.
当你调用时.attr,jQuery会检查集合中的每个对象是否具有该函数,getAttribute如果是这种情况,则假定它也具有函数setAttribute.
如果它没有函数getAttribute,那么它会将函数调用转发给.prop()函数,而prop将在内部执行:
elem[name] = value
Run Code Online (Sandbox Code Playgroud)
因此,如果将普通对象传递给jQuery,那么它只会设置其属性.
var a = {
}
$(a).attr('test', 'hello world');
console.dir(a) // for `a` the property `test` is setRun Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>Run Code Online (Sandbox Code Playgroud)
如果你向该对象添加一个getAttribute和setAttribute函数,那么jQuery将调用它们:
var a = {
getAttribute() {
},
setAttribute() {
console.log('setAttribute was called')
}
}
$(a).attr('test', 'hello world');
console.dir(a);Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>Run Code Online (Sandbox Code Playgroud)
但是,您应该始终假设,jQuery执行这些测试的方式和顺序可能会发生变化.而且,如果在文档中明确提到它,则只依赖它.
bro*_*ofa 19
我相信你$(document)没有提及document,因此答案是(非常简单):
document['key'] = 'value'
Run Code Online (Sandbox Code Playgroud)
例如在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"
Run Code Online (Sandbox Code Playgroud)
Rea*_*lar 11
jQuery只是document直接赋值.
$(document).attr('test', 'hello world');
console.log(document['test']); // prints "hello world"
Run Code Online (Sandbox Code Playgroud)