js模拟页面点击事件

1,720 阅读1分钟

//html
 <a :href="indexro" id="demo_click"></a>
//js
 data() {
     return { 
        indexro:'www.baidu.com'
    };
  },
   mounted(){
 const btn = document.getElementById('demo_click');
      btn.onclick = function () { //
        console.log('页面重新加载时触发点击事件')
      };
      simulateClick();
    // 2. 模拟 浏览器的鼠标点击事件
    // 2.1 可以触发 onclick 事件(先触发)
    // 2.2 可以触发 addEventListener 事件(后触发)
    // 2.3 jQuery 的事件绑定底层就是 addEventListener ,
      function simulateClick() { // 模拟 浏览器的鼠标点击事件
        const event = new MouseEvent('click', {
          view: window,
          bubbles: true,
          cancelable: true
        });
        btn.dispatchEvent(event);      
      }
  },
    // let path = window.location.protocol + "//" + this.indexro;
    // window.location.href = path;;执行失败+地址也失败

第三方短链接、模拟点击事件