我正在努力处理一个复杂的页面来选择几个元素。主要的一个是我需要读取/更改输入上的一些值的表单。 到目前为止,我已经使用此代码成功获得了表单:
var mainFrame = $(frames[1].document.body).contents().find("#mainFrame1");
好的,所以我尝试:
$(mainFrame.contents());
它返回空[]...如果我尝试
$(mainFrame[0].contents());
我收到错误:mainFrame[0].contents 不是函数...
但使用纯 JS:
mainFrame[0].contentDocument.getElementById("dataForm");
有效! 我想将其保留在 jQuery 中,并且我需要在同一框架内找到更多元素,因此我需要 mainFrame 变量可用于搜索所有这些元素...
为了帮助下面的答案找到完整的解决方案,我发布了 mainFrame 变量的 console.debug:
console.debug(mainFrame);
[frame#mainFrame, prevObject: b.fn.b.init[7], context: frameset#outerFrameSet, selector: "#mainFrame"]
0: frame#mainFrame
accessKey: ""
attributes: NamedNodeMap
baseURI: "https://edited"
childElementCount: 0
childNodes: NodeList[0]
children: HTMLCollection[0]
classList: DOMTokenList[0]
className: ""
clientHeight: 369
clientLeft: 0
clientTop: 0
clientWidth: 1150
contentDocument: document
->body
->children (here I can see the form I'm trying to select)
contentEditable: "inherit"
contentWindow: Window
dataset: DOMStringMap
dir: ""
draggable: false
firstChild: null
firstElementChild: null
frameBorder: "0"
hidden: false
id: "mainFrame"
innerHTML: ""
innerText: ""
isContentEditable: false
...
outerHTML: "<body ..."
continues...
最佳答案
$(mainFrame.contents());
有效,因为 mainFrame
是一个 jQuery 对象。 jQuery 方法只能应用于 jQuery 对象。
$(mainFrame[0].contents());
会产生错误,因为 mainFrame[0]
从 mainFrame
返回一个 DOM 节点> jQuery 对象。因此,您不能在其上使用 $.contents
。
要解决这个问题,我们可以像这样重写它:
$(mainFrame[0]).contents();
这获取 DOM 节点并将其转换回 jQuery 对象,从而允许我们在其上运行 $.contents();
。现在显然,当尝试将所有这些都用作另一个 jQuery 对象时,这可能会变得困惑,如下所示:$($(mainFrame[0]).contents());
。由于其中的一些原因,您可以使用像 $.first();
这样的方法,而不是返回 DOM 节点的数组。您还拥有 CSS :first-child
选择器。
最终,要使用 $.contents();
,您必须针对它使用 jQuery 对象,而不是 mainFrame[0]
返回的 DOM 节点。您的最终 JavaScript 版本可以正常工作,因为 JS 的函数是为处理 DOM 节点而构建的,而 jQuery 则可以处理对象。
关于jquery - 当 contentDocument 工作时,contents() 返回空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33440795/