我正在尝试测试这个小功能,我相信我写的一切都正确,但它没有出现在我的console.log中。我有什么想看的吗?
<style>
form{
width: 300px;
height: 75px;
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
}
</style>
<script>
var inputChange = function() {
var inputVal = document.getElementById("input").value;
console.log(inputVal)
};
</script>
</head>
<body>
<form>
<input id="input" type="text" name = "input" placeholder="Type Something"/>
<input type="submit" onclick ="inputChange()"/>
</form>
</body>
</html>
答案 0 :(得分:3)
类型inputs
的HTML submit
会在您点击它们时发送表单,因此脚本会被调用,并且您会短暂地看到输出,但页面会重新加载并且控制台正在清除。变化
<input type="submit" onclick ="inputChange()"/>
到
<input type="button" onclick ="inputChange()"/>
你应该好。
答案 1 :(得分:1)
这种情况正在发生,因为您的表单正在提交给自己,页面会在几秒钟内加载,以便您注意到差异。
有两种方法可以解决这个问题。
<强>一:强>
在表单元素中添加onsubmit="return false;"
属性。
<form onsubmit="return false;">
<input id="input" type="text" name = "input" placeholder="Type Something"/>
<input type="submit" onclick ="inputChange()"/>
</form>
以下是代码段:https://jsfiddle.net/ppn5ngwh/1/
<强>两个强> 修改你的javascript:
document.getElementsByTagName("form")[0].onsubmit = function() {return false;}
var inputChange = function() {
var inputVal = document.getElementById("input").html;
console.log(inputVal)
};