gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 16:57:30 24 4
gpt4 key购买 nike

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

关于JavaScript - onClick 将按钮 ID 或单击按钮的文本传递给函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29449230/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com