我们可以在对象中运行某些javascript吗?

Eas*_*yBB 1 javascript jquery object

我是JavaScript对象的新手,想知道我们是否可以在Object中运行JavaScript?这就是我想做的事情 -

$('.element').click(function () {
    var data = $(this).attr('data-home');
    if (data !== undefined) {
        var jsRun = {
            a: $('.more').show(),
            b: $('.div').show(),
            c: window.location = "www.url.com",
            d: location.reload()
        };
    }
    return jsRun[data];
});
Run Code Online (Sandbox Code Playgroud)

我写了返回jsRun因为我不太确定如果允许该怎么做以及如何让它运行我指定的代码.任何建议都会有所帮助

Asa*_*din 5

将所有这些包含在函数中,之后可以将它们作为对象的方法调用.

$('.element').click(function () {
    var data = $(this).attr('data-home'),
        jsRun; //your variable declaration is hoisted to here anyway
    if (data !== undefined) {
        jsRun = {
            a: function(){
               $('.more').show();
            },
            ...
        };
        return jsRun[data]();
    }
});
Run Code Online (Sandbox Code Playgroud)

结果,假设data是"a",$('.more')就是显示的结果.我已经在条件块中调用了调用,因为我假设你只想data要有一个值才会发生这种情况.