【问题标题】:Get JS object data from user input从用户输入中获取 JS 对象数据
【发布时间】:2018-01-07 19:13:40
【问题描述】:

接受标准:输入姓名并在点击或按下“返回”时让此人的分机返回 UI。

我正在寻找有关如何使其工作的建议。

UI

<html>
    <head>
        <title>SearchFunction</title>
    </head>
    <body>
        <script type="text/javascript">

            var extensionList = {

                Abby: '8845',   
                David: '8871',  
                Jim: '8890', 
                Lewis: '8804',
            };

            var returnLookUp = function(){
                var getInfo = document.getElementById("thisSearch");
                var SearchInfo = thisSearch.value;
                /*......?*/
            }

        </script>
        <form>
            <input id="thisSearch" type="text" placeholder="enter name">
            <button onClick = "returnLookUp();">Find</button>
            <input id="output" name="output" type="text" size="30">
            <br><br>
        </form>

    </body>
</html>

【问题讨论】:

  • return extensionList[SearchInfo];
  • 如果我输入名称“David”,我希望页面返回他的扩展名 8871。我可以使用 console.log(extensionList.Jim) 从 extensionList 对象获取信息,但我有无法做任何类似 console.log(extensionList.SearchInfo) 的事情。
  • 重新阅读我的代码。不是extensionList.SearchInfo,而是extensionList[SearchInfo]。如果searchInfo = 'Jim' 将等价于extensionList["Jim"]extentsionList.Jim 相同

标签: javascript html object search user-input


【解决方案1】:

没有明确定义按钮类型。所以默认情况下它将是按钮type ="submit"。在这种情况下,它将尝试提交表单。按钮type="button"可以使用或防止默认行为,preventDefault()可以使用

extensionList[thisSearch.value] 用于从对象中获取键的值,extensionList 是对象,thisSearch.value 将是与对象的键相同的输入

var extensionList = {

  Abby: '8845',
  David: '8871',
  Jim: '8890',
  Lewis: '8804',
};

var returnLookUp = function(e) {
  e.preventDefault();
  var getInfo = document.getElementById("thisSearch");
  document.getElementById("output").value = extensionList[thisSearch.value];

}
<form>
  <input id="thisSearch" type="text" placeholder="enter name">
  <button onClick="returnLookUp(event);">Find</button>
  <input id="output" name="output" type="text" size="30">
  <br><br>
</form>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-10
    • 1970-01-01
    • 1970-01-01
    • 2017-06-24
    • 2019-03-22
    • 1970-01-01
    • 1970-01-01
    • 2017-12-17
    相关资源
    最近更新 更多