0

我正在努力解决 JavaScrit 函数中的闭包范围。下面的函数应该创建三个具有不同图像的样本(有效),然后当它们被单击时,应该切换样式表。

问题是同一个对象被传递给switchTheme函数,即使单步执行显示theme第一个函数中的变量确实发生了变化。

var switcherConfig = {
    themes: 
        {
            'Orangeness': {
                folder: 'ui-lightness'
            },
            'Red Matter': {
                folder: 'blitzer'
            },
            'Flubber': {
                folder: 'south-street'
            }
        }
}
function createThemeSwitcher(placeholderSelector) {
    for (var themeName in switcherConfig.themes) {
        var theme = switcherConfig.themes[themeName];
        var anchor = $('<a/>')
            //.text(theme.title)
            .attr('title', theme.title)
            .attr('href', '#')
            .on('click', function () { switchTheme(theme); })
            // append to DOM etc
    }
}
function switchTheme(theme) {
    var themeDirectory = switcherConfig.baseDirectory + '/' + theme.folder + '/';
    // 'theme' variable is always the last in my 'themes' config object
}
4

3 回答 3

3

使用的值switchTheme(theme)将是调用函数时所处的状态,theme在您创建匿名回调时该值未绑定。使用闭包绑定该特定值:

.on('click', (function (t) {
    return function () { switchTheme(t); };
})(theme))
于 2012-09-25T09:02:45.450 回答
0

移动

var theme = switcherConfig.themes[themeName];

点击功能

function createThemeSwitcher(placeholderSelector) {
    for (var themeName in switcherConfig.themes) {

        var anchor = $('<a/>')
            //.text(theme.title)
            .attr('title', theme.title)
            .attr('href', '#')
            .on('click', function () { 
                         var theme = switcherConfig.themes[themeName];
                         switchTheme(theme); 
            })
            // append to DOM etc
    }
}
于 2012-09-25T09:03:18.937 回答
0

您可以使用.data如下方式而不是关闭(只是一种选择):

var switcherConfig = {
    themes: 
        {
            'Orangeness': {
                title:"Orangeness",
                folder: 'ui-lightness'
            },
            'Red Matter': {
                                title:'Red Matter',
                folder: 'blitzer'
            },
            'Flubber': {
                title:'Flubber',
                folder: 'south-street'
            }
        }
}
function createThemeSwitcher(placeholderSelector) {
    for (var themeName in switcherConfig.themes) {
        var theme = switcherConfig.themes[themeName];
        var anchor = $('<a/>')
            .data("theme",theme)
            .attr('title', theme.title)
            .attr('href', '#')
            .html(theme.title)
            .on('click', function () { switchTheme($(this).data("theme")); })
            $("body").append(anchor);
    }
}
function switchTheme(theme) {
    alert(theme.title)
}

演示

于 2012-09-25T09:12:24.670 回答