简体   繁体   English

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

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

I got the example from this link to work fine, trying to make it a little more dynamic where I would have multiple buttons and pass the button text or id to function doHelloWorld() here is my attempt 我从此链接获得了示例,使其工作正常,试图使它更具动态性,使我有多个按钮,并将按钮文本或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>

The execution context inside authenticate callback function is not button object anymore. authenticate回调函数中的执行上下文不再是按钮对象。 The simplest fix is to save reference proper this in local variable and use it like this: 最简单的解决方法是适当的保存参考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);
            }
        });
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM