我一直致力于一项功能,涉及使用 jquery 创建 HTML 表,该表将在页面加载时动态显示帐户列表,这是我毫无问题地实现的。
但是,我还要求在每一行中添加一个“onclick”事件,以便将我重定向到另一个网页,但这取决于我需要传递的参数。这是我的代码:
$(document).ready(function() {
var x = ['Visa-1234', 'Amex-9182', 'Visa-8162', 'Visa-9554'];
var message = 'No accounts found';
if (x.length > 0) {
message = 'Select an account to display the rewards information: ';
}
$('#message').text(message);
var tableContentHtml = '<table class="table-fill"><thead><tr><th class="text-left">Account</th></tr></thead><tbody class="table-hover">';
for (var i = 0; i < x.length; i++) {
tableContentHtml += '<tr><td class="text-left" onclick="goAnotherWebPage()">' + x[i] + '</td></tr>';
}
tableContentHtml += '</tbody></table>';
$(tableContentHtml).appendTo('#container');
});
function goAnotherWebPage(account) {
//do some logic here
}
方法“goAnotherWebPage”应该接收显示的相同帐户 ID,我对此没有问题,当我在创建表时将 x[i] 作为参数传递时出现问题:
onclick="goAnotherWebPage(x[i])"
那是行不通的,它说该帐户未定义。
有人可以给我提示或提供帮助以实现这一目标吗?提前致谢!
最佳答案
试试这个
for (var i = 0; i < x.length; i++) {
tableContentHtml += '<tr><td class="text-left" onclick="goAnotherWebPage(\'' + x[i] + '\')">' + x[i] + '</td></tr>';
}
$(document).ready(function() {
var x = ['Visa-1234', 'Amex-9182', 'Visa-8162', 'Visa-9554'];
var message = 'No accounts found';
if (x.length > 0) {
message = 'Select an account to display the rewards information: ';
}
$('#message').text(message);
var tableContentHtml = '<table class="table-fill"><thead><tr><th class="text-left">Account</th></tr></thead><tbody class="table-hover">';
for (var i = 0; i < x.length; i++) {
tableContentHtml += '<tr><td class="text-left" onclick="goAnotherWebPage(\'' + x[i] + '\')">' + x[i] + '</td></tr>';
}
tableContentHtml += '</tbody></table>';
$(tableContentHtml).appendTo('#container');
goAnotherWebPage = function(account) {
console.log(account);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="message"></div>
<div id="container"></div>
希望对您有所帮助。
关于javascript - 添加 onclick 事件到动态生成的表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47203648/