单击按钮时触发键盘事件

时间:2018-07-23 12:31:14

标签: javascript jquery angular typescript

add(){
  var newEvent = null; 
  try 
  {
    newEvent = document.createEvent("KeyEvents"); 
    newEvent.initKeyEvent("keypress", true, true, window,false, false, false, false, 0, 32); 
  }
  catch(ex) 
  {
    console.log(ex); 
    newEvent = document.createEvent("KeyboardEvent"); 
    newEvent.initKeyboardEvent('keypress', true, true, window, false, false, false, false, 32, 0); 
  }
          // e.preventDefault(); 
              document.getElementById('surname').dispatchEvent(newEvent);
}
<input type="text" id="surname" name="surname" placeholder="आडनाव" [(ngModel)]="surName">
<button class="btn btn-primary" (click)="add();" id="add" >Fire</button>

add(){
  var newEvent = null; 
  try 
  { 
    newEvent = document.createEvent("KeyEvents"); 
    newEvent.initKeyEvent("keypress", true, true,window,false, false, false, false, 0, 32); 
   }
   catch(ex) 
   { 
    console.log("aa ",ex); 
    newEvent = document.createEvent("KeyboardEvent"); 
    newEvent.initKeyboardEvent('keypress', true, true, window, false, false, false, false, 32, 0); 
    }
}
<button class="btn btn-primary" (click)="add();" id="add" >Fire</button>
上面的代码不起作用...不触发键盘事件, 我想在JQuery或javascript或angular 2中单击按钮时触发keypress事件(SpaceBar)。

0 个答案:

没有答案