[英]Function not working when placed in js file
Hi this is working when I include the code inside of my html but when I shift it out into myScript.js I get no results, can anyone point out where I've gone wrong with this as I'd like to be able to access this function across several pages?嗨,当我将代码包含在我的 html 中时,这是有效的,但是当我将其移出到 myScript.js 中时,我没有得到任何结果,任何人都可以指出我哪里出了问题,因为我希望能够访问这个function跨越几页?
I've also got the side issue that if I enter something, then delete the input value my filtered array shows all the options, is it possible to set this to a "" value if the input box contains no value?我还有一个附带问题,如果我输入一些内容,然后删除输入值,我的过滤数组显示所有选项,如果输入框不包含任何值,是否可以将其设置为“”值?
Thanks谢谢
function page_search(){ var pages = [ {name: "Test",url: "Test.html"}, {name: "Rest",url: "Rest.html"}, {name: "Best",url: "Best.html"}, ]; let input = document.getElementById('searchbar').value input=input.toLowerCase(); let x = document.getElementById('searchresults'); var results = []; for(var i=0;i<pages.length;i++){ if(pages[i].name.toLowerCase().indexOf(input) > -1) results.push("<a href='"+pages[i].url+"' target='_blank'>"+pages[i].name+"</a>") } if(results.length == 0) $(x).html("No Results Found"); else $(x).html(results.join("<br>")); return results; }
<html> <head> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> <script src="myScript.js"></script> </head> <body> <div class="searchbar"> <input type="text" id="searchbar" onkeyup="page_search()" placeholder="" value="Search.." maxlenght="25" autocomplete="off"/> </div> <div id="searchresults"></div> </body> </html>
I have added the code, it will definitely resolve your second issue of displaying "" when input box is empty.我已经添加了代码,它肯定会解决你的第二个输入框为空时显示“”的问题。 I am not able to replicate your first issue, can you please tell what is error you are getting?我无法复制你的第一个问题,你能告诉我你遇到了什么错误吗?
function page_search() { var pages = [{ name: "Test", url: "Test.html" }, { name: "Rest", url: "Rest.html" }, { name: "Best", url: "Best.html" }, ]; let input = $('#searchbar').val().toLowerCase() let x = $('#searchresults'); var results = []; if (input) { for (var i = 0; i < pages.length; i++) { if (pages[i].name.toLowerCase().indexOf(input) > -1) { results.push(`<a href="${pages[i].url}" target="_blank">${pages[i].name}</a>`); } } } else { $(x).html(""); return; } if (results.length == 0) $(x).html("No Results Found"); else $(x).html(results.join("<br>")); } var ele = document.getElementById('searchbar'); ele.addEventListener('keyup', page_search);
<html> <head> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> </head> <body> <div class="searchbarC"> <input type="text" id="searchbar" placeholder="Search.." maxlenght="25" /> </div> <div id="searchresults"></div> <script src="myScript.js" type="text/javascript"></script> </body> </html>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.