JavaScript - onClick 将按钮 ID 或单击按钮的文本传递给函数

JavaScript - onClick Pass button ID or text of the clicked button to a function

我从这个 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>

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);
            }
        });
    }
}