jquery函数范围

时间:2012-03-08 16:16:49

标签: javascript jquery html jquery-ui

我不在这里理解功能范围。单击时我有一个按钮显示带有textarea的对话框。在那个textarea里面,我用一个网址填充它,然后有人可以复制它们的相机设置。

<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。我做错了什么?

2 个答案:

答案 0 :(得分: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;
}

答案 1 :(得分: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');
});
});