gpt4 book ai didi

javascript - HTML/JavaScript - 输入值不更新(Element.value = Null)

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

你好,我今天刚开始,所以我很新。

我必须得到一个字符串,用户可以在网站上将其输入到我的 JavaScript 文件中。我发现我应该使用 document.getElementById("myID").value 来获取 html 站点上输入字段的值。这是我的问题:我不能在我的输入和按钮周围使用方括号,因为提交会强制重新加载网站,而我的功能不会有任何影响。

所以我必须即时将字符串获取到我的 JavaScript 文件中。

这就是我目前所有的:

<div id="searchDiv">
<input type="text" id="searchInput" placeholder="Search for Gifs..." value="" />
<input type="button" id="searchButton" value="Search"></button>
</div>

还有我的 JavaScript 文件:

var searchButton = document.getElementById("searchButton");
var searchInput = document.getElementById("searchInput").value;

searchButton.addEventListener("click",
function() {
function(parameter)
}
)...

因此,即使输入字段已被编辑,document.getElementById("searchInput").value; 也会返回 null。

我希望你能帮助我。

最佳答案

这是因为您甚至在单击按钮之前就存储了 searchInput 值,因此无论您输入什么内容,该值都将为空

尝试访问按钮的点击事件

检查这个片段

var searchButton =document.getElementById("searchButton");
var searchInput=document.getElementById("searchInput");
window.onload=function(){
searchButton.addEventListener("click",
function() {
alert(searchInput.value);
}
)
}
<div id="searchDiv">
<input type="text" id="searchInput" placeholder="Search for Gifs..." value="" />
<input type="button" id="searchButton" value="Search">

</div>

希望对你有帮助

关于javascript - HTML/JavaScript - 输入值不更新(Element.value = Null),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41404051/

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