基本上我试图通过 onclick 将 json 数组传递给函数
<button
onclick='showAccountOverviewModal("<%= accounts[j].name %>", `<%= accounts[j].bills%>`)'>
Click Me
</button>
但是,当我尝试通过 JSON.parse 解析字符串时,我意识到键和值都没有引号。有什么“好”方法来解决这个问题还是我需要使用正则表达式?
致以诚挚的问候
编辑
这是对应的函数:
function showAccountOverviewModal(accountName, accountBills) {
$("#accountModalOverviewTitle").text(accountName);
accountBills = JSON.parse(accountBills);
console.log(accountBills);
accountBills.forEach(bill => {
console.log(bill);
});
}
最佳答案
我将使用 data-* 属性重写您的代码。如果您不想要这种方法,可以忽略。
html
<button class="showaccountmodal"
data-accountName="<%= accounts[j].name %>
data-bill="<%= accounts[j].bills %>">Click Me</button>
jquery
$(".showaccountmodal").on('click', function() {
var accountname = $(this).data('accountName');
var bill = $(this).data('bill');
console.log(accountname);
console.log(bill);
accountBills.forEach(bill => {
console.log(bill);
});
} );
这里还有一个在 html 中存储 json 对象的引用 Store JSON object in data attribute in HTML jQuery
关于javascript - JS : Passed JSON-Array loses quotation marks,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56676898/