如何使我的 JavaScript 搜索高级?

我目前正在进行这样的 Javascript 搜索:


 <input type="text" id="link-box"/>

<input type="button" id="search-button" value="Search" 

    onclick="window.location = document.getElementById('link-box').value;"/>

剧本;


    <script type="text/javascript">


  function func(){

       window.location = document.getElementById('link-box').value;

  }


  onclick="func();"

  

</script>

这基本上做的是它打开用户输入的“值”。(例如;如果用户输入 1,它将打开 "www.example.com/1" )。


我想要做的是我想在搜索表单中添加另一个文本字段,如下所示:


<input type="text" id="link-box2"/>

现在我的输出中有两个字段和一个提交按钮。我想要的是,我希望第二个文本字段打开链接,为第一个字段中的用户输入值添加一个“/”。(例如;之前如果用户输入值“1”并打开“www.example.com/1”,现在使用第二个文本字段:如果用户在第一个文本字段中输入值“1”和值“2”在第二个文本字段中,它应该打开“www.example.com/1/2”)。简单地说,“link-box”(第一个文本字段)和“link-box2”(第二个文本字段)之间应该存在某种关系。我是 JavaScript 新手,所以请帮忙!!!


拉风的咖菲猫
浏览 114回答 3
3回答

翻翻过去那场雪

答案是您必须在获取价值代码之前使用您的网址。function func(){ window.location = "https://example.com/"+ document.getElementById('link-box').value; }或者function func(){ var searchKey = document.getElementById('link-box').value; window.location = "https://example.com/"+ searchKey; }如果您还想从其他输入中添加...您可以这样做function func(){&nbsp; &nbsp; &nbsp; &nbsp;var searchKey = document.getElementById('link-box').value;&nbsp; &nbsp; &nbsp; &nbsp;var searchKey2 = document.getElementById('link-box2').value;&nbsp; &nbsp; &nbsp; &nbsp;if(!searchKey2){&nbsp; &nbsp; &nbsp; &nbsp;window.location = "https://example.com/"+ searchKey;&nbsp; &nbsp; &nbsp; &nbsp;}else{&nbsp; &nbsp; &nbsp; &nbsp;window.location = "https://example.com/"+ searchKey + "/" + searchKey2;&nbsp; &nbsp; &nbsp; &nbsp;}&nbsp; }

青春有我

请试试这个。HTML:&nbsp;<input type="text" id="link-box"/>&nbsp;<input type="button" id="search-button" value="Search" onclick="search()"/>JS:<script>const search=()=>{&nbsp; let search-value = document.getElementById('link-box').value;&nbsp; if(!search-value){&nbsp; &nbsp; &nbsp;window.location = `https://example.com/${firstInput}`;}&nbsp; return;}</script>

梵蒂冈之花

// On input button click, call function func();<input type="button" id="search-button" value="Search"&nbsp;&nbsp; &nbsp; onclick="func()"/><script>function func() {&nbsp; // Gets the values of the 2 input fields.&nbsp; let firstInput = document.getElementById('link-box1').value;&nbsp; let secondInput = document.getElementById('link-box2').value;&nbsp;&nbsp;&nbsp; // Redirect the user to the specified URL with the values from the input boxes.&nbsp; window.location = 'https://example.com/' + firstInput + '/' + secondInput;}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript