如何使用纯JavaScript动态触发输入按钮事件

时间:2019-01-24 06:57:00

标签: javascript

我有一个输入,如果键码== 13,它将运行一个函数

如果用户单击该按钮,我也会在同一页面上有一个按钮,它应该触发与之关联的点击事件,同时它还应该使用javascript触发回车点击

代码如下所示

<input type="text" class="myInputValue">
<button class="myLink">submit</button>

(function(){
  var inputc = document.getElementsByClassName('myInputValue')[0];
  var submitbtn = document.getElementsByClassName('myLink')[0]
  inputc.addEventListener("keydown", function(e){
    if(e.keyCode == 13){
      alert("Entered")
    }
  });
  submitbtn.addEventListener("click", function(e){
    // here I need functionality which will fire enter key event too

  });
})();

http://jsfiddle.net/pnq6xfwa/

3 个答案:

答案 0 :(得分:1)

如果您不需要从按下的Enter按钮获取特定事件数据,而只需要运行相同的函数,则可以为匿名函数命名,例如package yraunaj.controller; import org.json.JSONException; import org.json.JSONObject; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.client.RestTemplate; @Controller public class HomeController { //get client id and client Secret by creating a app in //https://www.linkedin.com developers //and set your redirect url public String clientId="**********"; public String clientSecret="***********"; public String redirectUrl="http://localhost:8080/yraunaj/home"; //create button on your page and hit this get request @GetMapping("/authorization") public String authorization() { String authorizationUri="https://www.linkedin.com/oauth/v2/authorization?response_type=code&client_id="+clientId+"&redirect_uri="+redirectUrl+"&state=asasasasasas&scope=r_basicprofile%20r_emailaddress"; return "redirect:" + authorizationUri; } //after login in your linkedin account your app will hit this get request @GetMapping("/home") //now store your authorization code public String home(@RequestParam("code") String authorizationCode) throws JSONException { //to trade your authorization code for access token String accessTokenUri ="https://www.linkedin.com/oauth/v2/accessToken?grant_type=authorization_code&code="+authorizationCode+"&redirect_uri="+redirectUrl+"&client_id="+clientId+"&client_secret="+clientSecret+""; // linkedin api to get linkedidn profile detail String linedkinDetailUri = "https://api.linkedin.com/v1/people/~:(id,first-name,email-address,last-name,headline,picture-url,industry,summary)?format=json"; //store your access token RestTemplate restTemplate = new RestTemplate(); String accessTokenRequest = restTemplate.getForObject(accessTokenUri, String.class); JSONObject jsonObjOfAccessToken = new JSONObject(accessTokenRequest); String accessToken = jsonObjOfAccessToken.get("access_token").toString(); //trade your access token HttpHeaders headers = new HttpHeaders(); headers.add("Authorization", "Bearer " +accessToken); HttpEntity<String> entity = new HttpEntity<String>("parameters", headers); ResponseEntity<String> linkedinDetailRequest = restTemplate.exchange(linedkinDetailUri, HttpMethod.GET, entity, String.class); //store json data JSONObject jsonObjOfLinkedinDetail = new JSONObject(linkedinDetailRequest.getBody()); //print json data System.out.println(jsonObjOfLinkedinDetail); return "home"; } } ,并在您每次使用时使用希望运行 enter 键代码。然后,当您单击按钮时,可以通过processKey作为13方法的key参数。

请参见下面的工作示例:

processKey
function processKey(key) {
  if(key == 13){
    alert("Entered");
  }
}

(function(){
  var inputc = document.getElementsByClassName('myInputValue')[0];
  var submitbtn = document.getElementsByClassName('myLink')[0];
  
  inputc.addEventListener("keydown", e => processKey(e.keyCode));
  submitbtn.addEventListener("click", _ => processKey(13));
})();

答案 1 :(得分:0)

创建一个自定义事件并调度它。

submitbtn.addEventListener("click", function(e){
    var event = new CustomEvent("keydown", {
        keyCode: 13
    });
    inputc.dispatchEvent(event);
});

答案 2 :(得分:0)

相反,您可以在enter上调用btn事件。

(function(){
  var inputc = document.getElementsByClassName('myInputValue')[0];
  var submitbtn = document.getElementsByClassName('myLink')[0]
  inputc.addEventListener("keydown", function(e){
    if(e.keyCode == 13){
       submitbtn.click();
    }
  });
  submitbtn.addEventListener("click", function(e){
 alert('Hello');

  });
})();
<input type="text" class="myInputValue">
<button class="myLink">submit</button>

或者您可以为两个事件调用函数

(function() {
  var inputc = document.getElementsByClassName('myInputValue')[0];
  var submitbtn = document.getElementsByClassName('myLink')[0]
  inputc.addEventListener("keydown", function(e) {
    if (e.keyCode == 13) {
      test();
    }
  });
  submitbtn.addEventListener("click", function(e) {
    test();

  });
})();

function test(){
  alert('hello')
}
<input type="text" class="myInputValue">
<button class="myLink">submit</button>