JavaScript - onClick Pass按钮ID或单击按钮的文本到函数

时间:2015-04-04 17:14:39

标签: javascript dropbox-api

我从这个link得到的示例工作正常,尝试使其更加动态,我将有多个按钮并将按钮文本或ID传递给function doHelloWorld() 这是我的尝试

<!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>

1 个答案:

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