javascript - .css 函数在处理函数内部不起作用

标签 javascript jquery

我想更改命名函数内部的 css 属性,而不是处理单击事件。如果我在单击事件中定义的匿名函数中调用 .css ,它就会起作用。但是,我想在处理函数内定义的命名函数内调用 .css 。这是我的代码。

$(document).ready(function () {
    $('#popup').click(partial(coolTransition, $(this)));
});

function coolTransition(elem) {
    shrink();

    function shrink() {
        elem.css('background-color', '#000000');
    }
}

//used to implement partial function application so that I can pass a handler reference that takes arguments. 
//see http://stackoverflow.com/questions/321113/how-can-i-pre-set-arguments-in-javascript-function-call-partial-function-applic
function partial(func /*, 0..n args */ ) {
    var args = Array.prototype.slice.call(arguments, 1);
    return function () {
        var allArguments = args.concat(Array.prototype.slice.call(arguments));
        return func.apply(this, allArguments);
    };
}

预先感谢您的帮助。

最佳答案

在:

$(document).ready(function() {
    $('#popup').click(partial(coolTransition, $(this)));
});

$(this)$(document)。您需要 $(this) 来获取 $('#popup') 的上下文,为此您需要一个函数:

$(document).ready(function() {
    $('#popup').click((function() {
       return partial(coolTransition, $(this));
    })());
});

或者,您可以完全避免 $(this):

$(document).ready(function () {
    var $elm = $('#popup');
    $elm.click(partial(coolTransition, $elm));
});

实际上,partial 的整个用法似乎过于复杂。你为什么认为你需要它?最简单的方法是:

$(document).ready(function() {
    $('#popup').click(function() {
       coolTransition($(this));
    });
});

关于javascript - .css 函数在处理函数内部不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7379752/

相关文章:

javascript - 我想将一个字符串放入数组的每个值,如下面的代码所示。但我不想使用太多 if 运算符

javascript - 在 useEffect 的依赖数组中使用比较

javascript - If-Then-Else 用于我的简单 HTML 表单

jquery - 如何通过Webpack导入和使用jQuery库?

javascript - 将 html 数据附加到 Bootstrap 模式 javascript

javascript - SlidesJS - 一页上有多个 "product"示例 slider ?

javascript - 在 "Unique Morse Code Words"问题中,我在使用 JavaScript 时遇到问题

javascript - 无尽的动画、requestAnimationFrame 和调用堆栈限制

javascript - 如何通过 jquery 附加 -webkit-filter 属性

jquery - 如何为 keith-wood Jquery 倒计时插件设置 7 天倒计时