我有以下html:
<a class="expander" id="menMenu" onclick="expandMenu(this,event); return false;" href="" >Men</a>
当页面加载后我想要读取URL,如果它包含单词'men',我想要点击上面的链接。
这是我正在尝试的,控制台日志工作,但点击不会发生:
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();
}
};
答案 0 :(得分:0)
只需调用click通常会调用的expandMenu函数。
对于参数,您只需通过document.getElementById(&#34; menMenu&#34;)将其传递给函数即可引用锚对象。然后,对于该事件,您可以创建一个事件对象并指定它的类型等,并将其传递给该函数。
我还建议将你的(b =真)改为(b == true)。
b = true将始终返回true,因为您为b赋值为true。
将来如果您真的需要模拟点击,我建议您阅读调度事件。请参阅此参考:How to simulate a click with JavaScript?