javascript - JS : Passed JSON-Array loses quotation marks

标签 javascript html json

基本上我试图通过 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/

相关文章:

javascript - 如何使用 Javascript 检查当前鼠标按钮状态

html - 使用查询字符串表达 res.sendFile()

javascript - 尝试在 Jquery 中制作动画导航栏

javascript - 如何在javascript中的href标签中添加来自json数据的url

json - 移动浏览器上的 native JSON对象支持

javascript - addClass(undefined) 与 addClass(null)

javascript - 在 HTML 搜索期间隐藏 DIV 子元素

javascript - 如何在node js中设置和获取环境变量?

javascript - CSS 中可以自定义混合颜色吗?

python - 如何解析 Json 文件并搜索特定的关键字集?