gpt4 book ai didi

javascript - 尝试打印 json 中的关键变量

转载 作者:行者123 更新时间:2023-12-03 07:28:45 25 4
gpt4 key购买 nike

伙计们,我是新手,所以请帮助我..我正在尝试打印 json 中的变量键..但它不起作用..这是我的代码

<body>
<input type="text" name="name">
<button type="button" id="btn" onclick="constructJson(document.getElementById(" name "))">Click Me!</button>
<script type="text/javascript">
function constructJson(jsonKey) {
var jsonObj = {
"key1": "5"
};
jsonObj[jsonKey] = "2";
alert(jsonObj);
}
</script>
</body>

最佳答案

双引号内不能有双引号,并且应该使用输入值而不是 DOM 节点:

onclick="constructJson(document.getElementById('name').value)"

并且您需要设置输入的id:

<input type="text" name="name" id="name">

要显示 JSON,您需要使用 JSON.stringify:

function constructJson(jsonKey){
var jsonObj = {"key1": "5"};
jsonObj[jsonKey] = "2";
alert(JSON.stringify(jsonObj));
}
<input type="text" name="name" id="name">
<button type="button" id="btn" onclick="constructJson(document.getElementById('name').value)" >Click Me!</button>

关于javascript - 尝试打印 json 中的关键变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35893155/

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