将 JavaScript 元素作为变量传递

Pass Javascript element as variable

本文关键字:变量 JavaScript 元素      更新时间:2023-09-26

我正在为AngularJS应用程序做一些测试,我认为测试框架在这里不一定重要,但我正在尝试传递一个可选变量。此变量将指定我是否尝试获取传递给函数的 ID 的子元素

commonFunctions.elementDoesNotHaveAttribute('register-0', 'disabled', 'children[0].children[0]');

children[0].children[0]并不是真正的字符串,如果我删除引号,函数调用将失败,因为它找不到 .children[0] 的子对象

这是函数

function elementDoesNotHaveAttribute(id, attribute, child) {
    var hasElement = false;
    hasElement = casper.evaluate(function (id, attribute, child) {
        var element = document.getElementById(id);
        if (child) {
            element = element.child;
        }        
        return element.hasAttribute(attribute);
    }, id, attribute, child);
    if (hasElement) {
        casper.test.fail('element has' + attribute + ' but shouldn''t');
    } else {
        casper.test.pass('element didn''t have ' + attribute + ' and shouldn''t');
    }
}

如何更改这些方程的任一侧以最终评估函数中的element.children[0].children[0]

虽然我在评论中发布的"评估黑客"会起作用,但这是一个坏主意。相反,请考虑传递某种"转换"函数。

if( child) {
    element = child(element);
}

当调用时,比如说,children[0].children[0] ,你可以这样做:

commonFunctions.elementDoesNotHaveAttribute(
    'register-0',
    'disabled',
    function(e) {return e.children[0].children[0];}
);

函数将获取该元素并返回与其相关的其他内容。根据需要调整功能。