gpt4 book ai didi

javascript - 如何从插件内部访问查询中给出的上下文?

转载 作者:行者123 更新时间:2023-11-28 01:01:26 25 4
gpt4 key购买 nike

可以执行以下操作:

$(selector, context)

但是$.fn.pluginX如何找出给定的上下文是什么?例如:

$(selector, context).pluginX()
<小时/>

我有一种情况,第三方插件假定窗口/文档是当前窗口/文档。

<小时/>

编辑:

我假设文档是指“上下文”,但我猜它并不总是文档。就我而言,我正在执行诸如 $(sel, iframe.contentDocument).pluginX() 之类的跨文档内容,我想确保插件是否执行 $('body ').append,那么它应该执行 $('body', theSameDocumentContext).append。希望有帮助。

最佳答案

jQuery 元素有一个 .context 属性。您可以在插件中使用它:

$.fn.pluginX = function(){
console.log(this.context);
}

但这并不可靠,变异太多。 context 的值将始终为 document ,除非您传递 HTMLElement (像这样):

$('p', document.getElementsByTagName('div')[0]);

但是你可以传递不同的上下文:

//All working :
$('p', document.getElementsByTagName('div'));
$('p', document.querySelector('div'));
$('p', document.querySelectorAll('div'));
$('p', document.getElementByID('id'));
$('p', 'div');
$('p', $('div'));
$('p', $('div').add('p'));
///... ran out of ideas

现在,重要的是要知道传递上下文是 exactly the same has doing .find() :

$('p', 'div') === $('div').find('p');

此外,jQuery 在链接时始终存储前一个 jQuery 对象。如果是初次调用(没有使用遍历方法),则前一个对象将是文档。

了解了这些信息后,如果您想获取“真实”上下文,则可以获取最后一个元素。 jQuery 有属性 .prevObject。使用它:

$.fn.pluginX = function(){
console.log(this.prevObject);
}

关于javascript - 如何从插件内部访问查询中给出的上下文?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25570535/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com