gpt4 book ai didi

javascript - 如何在 localStorage 的 mirthril.js 中存储状态?

转载 作者:行者123 更新时间:2023-11-30 19:33:58 26 4
gpt4 key购买 nike

我试图在 localStorage 中保持复选框的状态,这里是 mithril 2.0 的代码,但它不会在 oninit() 之后重绘复选框。

<!doctype html><head>                                                           
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="//unpkg.com/mithril@next/mithril.min.js"></script>
</head>
<body>
<script>
var state = false
var ConfigPage = {
view: function(vnode) {
return m('input[type=checkbox]', {
value: state,
onchange: function(e) {
state = (e.target.value !== 'true')
if (localStorage !== undefined) {
var s = JSON.stringify(state)
console.log("save state in t1:", s)
localStorage.setItem('t1', s)
}
}
})
}
}
m.mount(document.body, {
oninit: function(vnode) {
if (localStorage !== undefined) {
var v = localStorage.getItem("t1")
if (v !== null) {
state = JSON.parse(v)
console.log("load state from t1:", v)
}
}
},
view: function() {
return m(ConfigPage)
}
})
</script>
</body></html>

最佳答案

这个问题是由于checked属性设置不当造成的,这里是修改后的代码

<!doctype html><head>                                                           
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="//unpkg.com/mithril@next/mithril.min.js"></script>
</head>
<body>
<script>
var state = false
var ConfigPage = {
view: function(vnode) {
return m('input[type=checkbox]', {
value: state,
checked: state, // ADD THIS
onchange: function(e) {
state = e.target.checked // use the checked value
if (localStorage !== undefined) {
var s = JSON.stringify(state)
console.log("save state in t1:", s)
localStorage.setItem('t1', s)
}
}
})
}
}
m.mount(document.body, {
oninit: function(vnode) {
if (localStorage !== undefined) {
var v = localStorage.getItem("t1")
if (v !== null) {
state = JSON.parse(v)
console.log("load state from t1:", v)
}
}
},
view: function() {
return m(ConfigPage)
}
})
</script>
</body></html>

关于javascript - 如何在 localStorage 的 mirthril.js 中存储状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56142665/

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