简体   繁体   English

模拟页面加载后的点击-使用Javascript,而不是JQuery

[英]Simulating a click after page load - Javascript, not JQuery

I have the following html: 我有以下html:

<a class="expander" id="menMenu" onclick="expandMenu(this,event); return false;" href="" >Men</a>

When the page has loaded I want to read the URL and, if it contains the word 'men', I want the above link to be clicked. 页面加载完毕后,我想阅读该URL,如果其中包含“ men”一词,则希望单击上面的链接。

Here's what I'm trying, console log works but the click doesn't happen: 这是我正在尝试的操作,控制台日志有效,但单击不会发生:

window.onload = function() {
      var newURL = window.location.protocol + "//" + window.location.host + "/" + window.location.pathname;
      var myWord = 'men';
      var a = new RegExp('\\b' + myWord + '\\b');
      var b = (a.test(newURL));
      if(b=true){
          console.log('true'); // this shows 'true' in console
          document.getElementById("menMenu").click();    
      }
  };

Just call the expandMenu function that the click would normally call. 只需调用click通常会调用的expandMenu函数。

For the parameters you need to reference the anchor object by simply passing it to the function via document.getElementById("menMenu"). 对于参数,您需要通过简单地通过document.getElementById(“ menMenu”)将锚对象传递给函数来引用锚对象。 Then for the event, you can create an event object and assign it's type, etc, and pass it to the function as well. 然后,对于事件,您可以创建一个事件对象并为其分配类型,等等,并将其传递给函数。

I'd also suggest changing your (b=true) into (b==true). 我还建议您将(b = true)更改为(b == true)。

b=true will always return true since you are assigning b the value of true. 由于您为b分配了true值,因此b = true将始终返回true。

In the future if you really need to simulate a click, I suggest reading up on dispatching events. 将来,如果您真的需要模拟点击,建议您阅读调度事件。 See this for reference: How to simulate a click with JavaScript? 请参阅此内容以供参考: 如何使用JavaScript模拟点击?

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

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