【问题标题】:Using JS to read from a JSON file when button is clicked单击按钮时使用 JS 从 JSON 文件中读取
【发布时间】:2016-03-28 14:51:18
【问题描述】:

我正在尝试解决用户在搜索框中输入值、按下搜索按钮并通过 onClick 事件将搜索词与 JSON 文件中的值进行比较的问题。目前我不知道 jQuery,所以如果可以在解决方案中避免这种情况,我将不胜感激!到目前为止我所拥有的是:

<div id="searchb">
    <button onclick="userSearch()">Search</button>
</div>

这是一个用于调用处理 JSON 文件的 userSearch 函数的搜索按钮的简单 div:

<script>
<!--Function which compares inputted name to names in the .json file. -->
function userSearch(thearr) {

... <!-- All of the code that compares the values -->

console.log();
}
</script>

<script src="filepath on my machine">
</script> <!-- Source path to .json file for script -->

我遇到的问题是 onClick 事件中的函数没有传递任何参数,因为在到达脚本标记之前未定义 userSearch 的参数。当我运行这个“小程序”时,我收到一个错误,指出参数 thearr 未定义。

文件路径是正确的,因为我将它用于类似的问题,该问题在页面加载时从 JSON 文件自动生成结果,这似乎是按钮单击问题。任何有关如何解决此问题的想法将不胜感激!谢谢。

编辑:按要求搜索框 HTML

<div id="textboxes">
<textarea id="input1" placeholder="First Name" rows="1" cols="10">
</textarea>
<textarea id="input2" placeholder="Surname" rows="1" cols="10"></textarea>
</div>

【问题讨论】:

  • 你能在用户输入姓名的搜索框中添加html吗?
  • @KarlP.Galvez 最后添加了它。

标签: javascript html arrays json file


【解决方案1】:

根据您的问题,听起来您需要从用户输入中获取值。对于 userSearch(thearr),我不确定您期望 thearr 是什么。您可以像这样获取用户输入的值:

 function userSearch() {
        var firstName = document.getElementById("input1").value;
        var surName = document.getElementById("input2").value;
        console.log(firstName + " " + surName);
    }

注意:如果您希望处理多个名字/姓氏,您应该重新考虑架构。使用当前设置执行此操作的逻辑编写起来并不简单,更重要的是没有必要。

【讨论】:

    猜你喜欢
    • 2021-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多