简体   繁体   English

带链接的Javascript搜索功能

[英]Javascript Search Function with Links

I'm having a few issues with my javascript search bar. 我的javascript搜索栏出现了一些问题。 I set up a simple function that I found on here to search the contents of div tags. 我设置了一个简单的函数,可以在这里找到div标签的内容。 Works great, but I want to create links that set the value of the search, so I can break up my page by categories as well. 效果很好,但我想创建设置搜索值的链接,因此也可以按类别细分页面。 The search bar is set up with an onKeyup event, so the function triggers with the input from the keyboard. 搜索栏设置了onKeyup事件,因此该功能通过键盘输入触发。 How can I make the function fire with clicking the hyperlink to the function that inputs the value? 单击指向输入值的函数的超链接,如何使该函数触发? Code below: 代码如下:

function myFunction() {
  var input = document.getElementById("Search");
  var filter = input.value.toLowerCase();
  var nodes = document.getElementsByClassName('connect-cat');


  for (i = 0; i < nodes.length; i++) {

  if (nodes[i].innerHTML.toLowerCase().includes(filter)) {
      nodes[i].style.display = "block";
    } else {
      nodes[i].style.display = "none";
    }
  }
}

function experienceMore() {
    document.getElementById("Search").value = "Experience more campaign";
    }

function firstChoice() {
    document.getElementById("Search").value = "First choice";
    }

And the HTML for the search bar 和搜索栏的HTML

      <input type="text" id="Search" onKeyup="myFunction()" Placeholder="Please enter a search term...">

It should be noted that the functions are working, however to activate the search one would have to hit the return key or add a space to the search bar. 应该注意的是,这些功能正在起作用,但是要激活搜索,必须按下返回键或在搜索栏上增加一个空格。

Thanks in advance! 提前致谢!

simplest thing, just call myFunction 最简单的事情,只需调用myFunction

function firstChoice() {
  document.getElementById("Search").value = "First choice";
  myFunction()
}

Or you can dispatch an event. 或者,您可以调度事件。

var el = document.getElementById("Search")
el.value = "First choice"
var e = document.createEvent('HTMLEvents');
e.initEvent("keyup", false, true);
el.dispatchEvent(e)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM