2015-04-04 63 views
1

我从这个link得到了这个例子正常工作,试图让它更加动态一点,我会有多个按钮并传递按钮文本或ID到function doHelloWorld() 这里是我的尝试JavaScript - onClick通过按钮ID或点击按钮的文本功能

<!doctype html> 
<html> 
<head> 
<script src="https://www.dropbox.com/static/api/dropbox-datastores-1.0-latest.js"></script> 
<link rel="stylesheet" href="style.css"> 
</head> 
<body> 
<center> 
    <button id="writeButton1"><font size="12">text one</font></button><br> 
    <button id="writeButton2"><font size="12">text two</font></button><br> 
    <button id="writeButton3"><font size="12">text three</font></button> 
</center> 

<script> 
    var client = new Dropbox.Client({ key: 'YOUR-APP-KEY-HERE' }); 

    // Try to complete OAuth flow. 
    client.authenticate({ interactive: false }, function (error, client) { 
     if (error) { 
      alert('Error: ' + error); 
     } 
    }); 

    for (var i = 1; i <= 3; i++){ 
     document.getElementById('writeButton' + i).onclick = function() { 
      client.authenticate(function (error, client) { 
       if (error) { 
        alert('Error: ' + error); 
       } else { 
        doHelloWorld(this.id); 
       } 
      }); 
     } 
    } 

    function doHelloWorld(i) { 
     client.writeFile('hello.txt', 'Hello, World!' + i, function (error) { 
      if (error) { 
       alert('Error: ' + error); 
      } else { 
       alert('File written successfully!'); 
      } 
     }); 
    } 

</script> 

+0

将属性添加到每个按钮的onclick =“函数名(ID);”并在函数中返回,您可以在参数中获取它。简单 – 2015-04-04 17:27:00

回答

2

authenticate回调函数的执行上下文不是按钮对象了。最简单的解决方法是保存正确参照this在本地变量并使用它是这样的:

for (var i = 1; i <= 3; i++) { 
    document.getElementById('writeButton' + i).onclick = function() { 
     var button = this; 
     client.authenticate(function (error, client) { 
      if (error) { 
       alert('Error: ' + error); 
      } else { 
       doHelloWorld(button.id); 
      } 
     }); 
    } 
}