为什么html调用js函数获取html无法找到变量错误?

时间:2016-09-25 08:57:13

标签: javascript jquery html function

我有js / jquery对话框,它有一些html输入按钮,允许用户选择颜色。单击时按钮应调用javascript函数changeColor。我已将代码缩减到最小集合,但是当单击其中一个颜色按钮时,我得到一个html"参考错误:无法找到变量:changeColor"错误。不确定我错过了什么。

function changeColor(themeColor) {
    var a = 1;
}

$('#change-theme').on('click', function() {
    $('#theme').dialog({
        width: 500,
        resizable: false,
        show: 'slide',
        autoOpen: false,
        modal: true,
        buttons: [{
            text: "Save",
            tabIndex:-1,
            'class':'dialog3_buttons',
            click: function(event) {
                $(this).dialog("close");
                return true;
            }
        }, {
            text: "Cancel",
            tabIndex:-1,
            'class':'dialog3_buttons',
            click: function(event) {
                $(this).dialog("close");
                return false;
            }
        }]
    })
    .height("auto");

    $("#theme").dialog( "option", "title", "Theme Picker - click a color to preview" );
    $("#theme").html(
        "<input type='button' class='color-button white-btn' id='color-button' name='white' onclick='javascript:changeColor()' >" +
        "<input type='button' class='color-button black-btn' id='color-button' name='black' onclick='javascript:changeColor()' >"
        );
    $('#theme').dialog('open');
});

2 个答案:

答案 0 :(得分:2)

如果你想像在你的例子中那样从html调用它,你必须将该函数分配给全局可用范围

将此行添加到您的代码中

window.changeColor = changeColor;

请参阅此工作示例https://jsfiddle.net/09ghrhap/1/

答案 1 :(得分:0)

我猜您需要将该功能放入<head></head>