2012-03-08 105 views
0

我不理解函數範圍。點擊時我有一個按鈕顯示一個帶有textarea的對話框。在那個textarea裏面,我用一個網址填充它,然後有人可以爲他們的相機設置進行復制。jquery函數範圍

<button id="axis-details" onclick="apikey('<?php echo $result_cameras[$i]["camera_hash"]; ?>');">API Key</button> 

function apikey(camerahash) 
{ 
    var $key = "http://myhost.com/notify.php/" +camerahash; 
    return $key; 
} 

$(document).ready(function() { 
    var $dialog = $('<div></div>'); 
$dialog.append('Please copy this key for camera setup: ') 
     .append('<p><textarea id=\"textbox\">'+apikey(camerahash)+'</textarea></p>') //ERROR here that camerahash is not defined 
     .append('<p>For more information see: <a href=\"http://www.myhost.com/forum/2-quickstart-docs\">setup</a></p>'); 
$dialog.dialog({ 
    autoOpen: false, 
    title: 'API Key' 
}); 

$('#axis-details').click(function(e) { 
    e.preventDefault(); 
    $dialog.dialog('open'); 
}); 
}); 

函數apikey(camerahash)確實返回我期望的值。我得到上面指出的camerahash未定義的錯誤。我究竟做錯了什麼?

+0

在你的代碼永遠不會初始化'camerahash'沒有你忘了什麼? – 2012-03-08 16:20:52

+0

指出camerahash未定義的錯誤是因爲camerahash沒有定義......不知道可以得到多少明確 – jbabey 2012-03-08 16:25:54

回答

2

我想這是你真正想要的東西:

<button id="axis-details">API Key</button> 

function apikey(camerahash) 
{ 
    var $key = "http://myhost.com/notify.php/" +camerahash; 
    return $key; 
} 

$(document).ready(function() { 
    var $dialog = $('<div></div>'); 
$dialog.append('Please copy this key for camera setup: ') 
     .append('<p><textarea id=\"textbox\">'+apikey(<?php echo $result_cameras[$i]["camera_hash"]; ?>)+'</textarea></p>') //ERROR here that camerahash is not defined 
     .append('<p>For more information see: <a href=\"http://www.myhost.com/forum/2-quickstart-docs\">setup</a></p>'); 
$dialog.dialog({ 
    autoOpen: false, 
    title: 'API Key' 
}); 

$('#axis-details').click(function(e) { 
    e.preventDefault(); 
    $dialog.dialog('open'); 
}); 
}); 
+0

我希望那樣簡單。 php代碼通過循環打印出camera_hash。感謝您的幫助,我想我遇到了更大的問題。 – Tom 2012-03-08 18:13:50

+0

@TomPepernic看看這個:http://jsfiddle.net/tUQbQ/ – Lazarus 2012-03-09 10:55:31

2

它在你的apikey函數只定義,您還需要從您的jQuery的方法,通過它,

.append('<p><textarea id=\"textbox\">'+apikey('<?php echo $result_cameras[$i]["camera_hash"]; ?>')+'</textarea></p>') 

或者更簡單,修改你的函數不需要輸入,

function apikey() 
{ 
    var $key = "http://myhost.com/notify.php/" +'<?php echo $result_cameras[$i]["camera_hash"]; ?>'; 
    return $key; 
} 
+0

或者更容易一些,請不要使用函數! – Archer 2012-03-08 16:26:06

+0

@阿徹的確如此:P – Andrew 2012-03-08 16:27:43