【问题标题】:How to search through the array and output answer in html using javascript如何使用 javascript 在 html 中搜索数组并输出答案
【发布时间】:2015-11-12 04:20:03
【问题描述】:

我是 javascript 新手,我正在用 html 制作网站。

我制作了网站标题,并在其旁边放置了表单类型的文本输入和提交类型的按钮。

我想做的是当我在搜索框中输入内容并按提交时, 我希望它输出我将在 html 正文中使用的函数的结果。

目前我得到的代码是:

var button = document.getElementById("button");

var data = ["Jaws, Jaws 1, Jaws 2, Jaws 3, Space Jame, Big Fish, The illusionit"];

button.onclick = function() {
var formInput = document.getElementById(formInput).value;
for (i=0; i<data.length;i++){
    if(data[i].indexOf(formInput) != -1) {
        alert(data[i]);
    }
    else {
        alert("We do not have any data like that. Sorry!");
    }
};

这是 java 脚本代码,这是我的 hmtl 代码:

<body>
<div id="head">
    <div id="logo">
        <img src="img/logo.png" style="height:50px;">
    </div>
    <div id="search">
        <form>
            <input type="text" name="search"   class="search" id="formInput">
            <input type="submit" value="OK"    class="button" id="button">
        </form>
    </div>
</div>
<div id="output">
    <script>
    var html = "The outputs are going to be: "
    document.getElementById('output').innerHTML = html;
    </script>
</div>
<div id="footer">
</div>

因此,例如,如果我输入 Jaws,我希望它返回 Jaws , Jaws 1, Jaws 2, Jaws 3

这不工作任何人都可以建议如何使它工作? 我知道我可以使用 php 或其他语言,但我只想使用 javascript 和 html 来完成

谢谢!!!

【问题讨论】:

  • 查看如何在 JavaScript 中创建字符串数组。您的数组当前有一个元素,一个很长的字符串,而不是多个字符串元素。
  • 我也会考虑学习使用像 jQuery 这样的库,而不是单独使用原生 Javascript。这将使事件处理更容易,并且跨浏览器更兼容。

标签: javascript html arrays output


【解决方案1】:

您可以使用javascript filter 来获取过滤后的数据

这样试试

var formInput = document.getElementById(formInput).value;
var dataList=data.filter(function(x){ return x.indexOf(formInput)>-1; });
for (i=0; i<dataList.length;i++){
  console.log(dataList[i]);
}

我觉得你的数组不好看

尽量保持你的数组是这样的

var data = ["Jaws","Jaws 1","Jaws 2","Jaws 3","Space Jame","Big Fish","The illusionit"];

而不是

var data = ["Jaws, Jaws 1, Jaws 2, Jaws 3, Space Jame, Big Fish, The illusionit"];

【讨论】:

  • 我按照您告诉我的方式更改了它,但它没有出现在那里。有什么我应该在 html 文件中调用以使其工作的吗?
  • @comp 你能提供小提琴吗?
【解决方案2】:

var array = ["a","b","c"];
function searchIT(){
  var inputVal = document.getElementById("inputTxt").value;
  console.log(inputVal);
  if(array.indexOf(inputVal) !== -1){
    document.getElementById("result").innerHTML = "The output is : "+ inputVal;
  } else {
    document.getElementById("result").innerHTML = "There is no such element";
  }
}
  <input type="text" id="inputTxt">
  <button onclick="searchIT();">Search</button>
<div id="result">
</div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多