2016-09-25 43 views
0

我有js/jquery對話框有一些html輸入按鈕,允許用戶選擇一種顏色。點擊按鈕應該調用JavaScript函數changeColor。我已經將代碼減少到最小集合,但是當單擊其中一個顏色按鈕時,我得到一個html「參考錯誤:無法找到變量:changeColor」錯誤。不知道我錯過了什麼。爲什麼html調用js函數獲取html無法找到變量錯誤?

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'); 
}); 
+0

爲什麼不簡單使用'onclick ='changeColor()' –

+0

除非頁面上的第一個腳本不是JavaScript,否則不需要'javascript:'標籤。你可以刪除它 – mplungjan

回答

2

您必須將功能分配給一個全局範圍,如果你想從HTML調用它就像你在你的例子

做這行添加到您的代碼

window.changeColor = changeColor; 

見這個工作例子https://jsfiddle.net/09ghrhap/1/

+0

非常感謝你!我永遠不會認爲這是問題。最受讚賞。 – Tim

+0

@Tim:不客氣。如果你想看看,我已經更新了一下這個例子。 – Ma3x

+0

只需將$(function/$(document).ready – mplungjan

0

我想你需要把功能放入<head></head>

相關問題