JavaScript 对象方法和使用<input>值

JavaScript object methods and working with the <input> values

本文关键字:input 对象 方法 JavaScript      更新时间:2023-09-26

我正在研究JavaScript中的自定义秒表,该秒表将脱机运行。并尝试实现一些将保存在HTML5 localStorage中的基本设置(如果尚未保存localStorage,则使用默认值)。

所以我有设置.html窗口,可以容纳所有输入:

<html>
<head>
<title>OS Stopky - Settings</title>
<link rel="stylesheet" type="text/css" href="osstopky.css">
<script type="text/javascript" src="settings.js"></script>
</head> 
<body>
<div class="settingswrapper">
<br>
<table id="settingstable">
<tr>
<td>Counter font size</td>
<td><input type="text" id="settCounterSize" size="5" > [px]</td>
</tr>
</table>
</div>
<script>
Settings.load();
</script>
</body>
</html>

在设置中.js我尝试创建对象来保存设置并使用它们:

var Settings = {
    settCounterSize: 66,
    load: function() {
        if (localStorage.settCounterSize) {
            document.getElementById("settCounterSize").value = localStorage.settCounterSize;
        } else {
            document.getElementById("settCounterSize").value = this.settCounterSize;
        }
    },
    save: function() {
        localStorage.settCounterSize =  document.getElementById("settCounterSize").value;           
    },
    loadDefaults: function() {
    }
};

但是,一旦设置.html页面加载,输入字段"setCounterSize"将保持空白。

我想我需要一双新鲜的眼睛,被这个看似简单的调用困了几个小时,从外部文件中阅读 W3 学校和 Javascript html 调用外部对象,我找不到我的问题所在。

谢谢你的时间!

您使用哪种浏览器,哪个版本?对我来说,它似乎有效。检查这个jsfiddle:http://jsfiddle.net/08ca8hau/

同样正如这些家伙评论的那样,检查任何控制台错误并将其粘贴到此处(如果有)。

var Settings = {
    settCounterSize: 66,
    load: function() {
        if (localStorage.settCounterSize) {
            document.getElementById("settCounterSize").value = localStorage.settCounterSize;
        } else {
            document.getElementById("settCounterSize").value = this.settCounterSize;
        }
    },
    save: function() {
        localStorage.settCounterSize =  document.getElementById("settCounterSize").value;           
    },
    loadDefaults: function() {
    }
};
Settings.load();
<table id="settingstable">
<tr>
<td>Counter font size</td>
    <td><input type="text" id="settCounterSize" size="5" /> [px]</td>
</tr>
</table>