gpt4 book ai didi

javascript - 键值对中的随机变量未解释为变量

转载 作者:行者123 更新时间:2023-11-30 15:46:52 26 4
gpt4 key购买 nike

我尝试使用 key:value 对将一些值存储在本地存储中。我希望 keyMath.random() 中的随机值,但我的值未被视为变量

这是 fiddle

https://jsfiddle.net/ps4xs60x/27/

代码

$(document).ready(function () {
$(document).on('click', '.btn-primary', function(){
var num = Math.random();
$('.table tbody').append('<tr class="child"><td>one</td><td><button id="'+num+'" onClick="ae(this.id); function ae(clicked_id) {var items = []; var entry = {\'num\': clicked_id}; items.push(entry);localStorage.setItem(\'entry\',JSON.stringify(items));alert(localStorage.getItem(\'entry\',JSON.stringify(items)));}" type="button" class="invite ">Invite</button></td></tr>');
});
});

如何使 num 被视为一个变量?

最佳答案

免责声明:

因此 localStorage 在这些片段中的作用不大,但请参阅下面的代码或 this forked fiddle .

代码修改

  1. 将函数 ae() 移出 onClick 属性并将其定义为常规 JS 函数。
  2. 假设您想将每个点击的数字添加到 localStorage 元素 entry 数组,那么您需要每次都将其解析为 json(如果已设置)而不是制作一个新阵列。
  3. 不使用 onclick 属性,而是为具有类名 invite 的元素添加点击处理程序,就像您为具有类名 的元素所做的那样btn-primary...

function ae(event) {
var items = JSON.parse(localStorage.getItem('entry'));
if (items == null || typeof items !== 'object') {
items = [];
}
var entry = {
'num': event.target.id
};
items.push(entry);
localStorage.setItem('entry', JSON.stringify(items));
alert(localStorage.getItem('entry'));
}
$(document).ready(function() {
$(document).on('click', '.invite', ae);
$(document).on('click', '.btn-primary', function() {
var num = Math.random();
$('.table tbody').append('<tr class="child"><td>one</td><td><button id="' + num + '"type="button" class="invite ">Invite</button></td></tr>');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="table">
<tbody></tbody>
</table>

<button class="btn-primary">Add Row
</button>

关于javascript - 键值对中的随机变量未解释为变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39940476/

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