为什么不评估正确返回DOM节点? [英] Why doesn't this.evaluate return DOM nodes correctly?

查看:132
本文介绍了为什么不评估正确返回DOM节点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过 evaluate()方法从网页获取对象,以便我可以在范围之外使用它评价。使用名称 symbol 选择的元素是< select> 标记,其中包含148 < options> ; (=下拉菜单)。

I'm trying to get an object from a web page through the evaluate() method so I can work with it outside the scope of evaluate. The element selected with name symbol is a <select> tag with 148 <options> (=dropdown menu).

casper.then(function () {
    var elmnt = this.evaluate(function () { return document.getElementsByName("symbol")[0]; });
    console.log(elmnt.options[14].index);
});

//Returns TypeError: 'null' is not an object (evaluating 'elmnt.options[14].index')

casper.then(function () {
    var elmnt = this.evaluate(function () { return document.getElementsByName("symbol")[0].options[14].index; });
    console.log(elmnt);
});

//Returns 14

所以看起来喜欢通过 evaluate()方法不正确地返回它,因为这可以正常工作:

So it looks likes returning an object through the evaluate() method returns it incompletly since this works correctly :

casper.then(function () {
    var elmnt = this.evaluate(function () { return document.getElementsByName("symbol")[0]; });
    console.log(elmnt.options.length);
});

//Returns 148

所以我可以访问选项属性,只要我不读数组。奇怪没有?

So I can access options attributes as long as I don't read the array. Strange no ?

推荐答案

这是有道理的,因为 elmnt.options in最后一个片段是一个包含 undefined 值的数组。所以你知道元素的数量,但不知道它们的值。原因是DOM节点无法从页面上下文传递。 文档说:

It makes sense, because elmnt.options in the last snippet is an array full with undefined values. So you know the number of elements, but not their values. The reason is that DOM nodes cannot be passed from page context. The docs say:

注意: evaluate函数的参数和返回值必须是一个简单的原始对象。经验法则:如果它可以通过JSON序列化,那就没关系了。

Note: The arguments and the return value to the evaluate function must be a simple primitive object. The rule of thumb: if it can be serialized via JSON, then it is fine.

闭包,函数,DOM节点等将 not 工作!

Closures, functions, DOM nodes, etc. will not work!

所以你要么在页面上下文中做所有事情(评估)或者获得要使用的DOM节点的表示。我认为这不是你想要的。

So either you do everything inside of the page context (evaluate) or you get a representation of the DOM nodes that you want to work with. Which I think is not what you want.

var elmnt = this.evaluate(function () {
    return [].map.call(document.getElementsByName("symbol")[0].options, function(option){
        return {text: option.innerText, value: option.value};
    });
});

这篇关于为什么不评估正确返回DOM节点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆