将JavaScript代码添加到现有事件

时间:2016-10-27 14:49:02

标签: javascript jquery html

我想在现有的JavaScript事件中添加一个函数:

<input type="text" value="" maxlength="2048" accesskey="S" title="Rechercher..." id="ctl00_ctl42_g_c33cc49a_f2b3_4d8f_9da7_c43b759a91ea_csr_sbox" autocomplete="off" autocorrect="off" onkeypress="if (Srch.U.isEnterKey(String.fromCharCode(event.keyCode))) { $getClientControl(this).search(this.value);return Srch.U.cancelEvent(event); }" onkeydown="var ctl = $getClientControl(this);ctl.activateDefaultQuerySuggestionBehavior();" onfocus="var ctl = $getClientControl(this);ctl.hidePrompt();ctl.setBorder(true);" onblur="var ctl = $getClientControl(this);ctl.showPrompt();ctl.setBorder(false);" class="ms-textLarge ms-srch-sbLarge-fullWidth">

我想将此功能添加到事件onkeydown

if(window.location.href.indexOf("#k=") > -1) { 
    $("#reset").show();
}

2 个答案:

答案 0 :(得分:1)

为什么不使用addEventListener

来使用更少侵入性和更易读的js来编写js
var element = document.querySelector( ".ms-srch-sbLarge-fullWidth" );
element.addEventListener( "keydown", function(){
  var ctl = $getClientControl(this);
  ctl.activateDefaultQuerySuggestionBehavior();
  if(window.location.href.indexOf("#k=") > -1) { 
    $("#reset").show();
  }
});

答案 1 :(得分:0)

纯JavaScript Element.addEventlistener()

&#13;
&#13;
document.getElementById("button").addEventListener("click", function() {
  //excute some 1
  console.log("first event fired");
}, false);

document.getElementById("button").addEventListener("click", function() {
  //excute some 2
  console.log("appended event fired in the same time");
}, false);
&#13;
<button id='button'>click</button>
&#13;
&#13;
&#13;

JQuery $("selector").on();

&#13;
&#13;
$("#button").on("click",function(){
console.log("first call");
});

$("#button").on("click",function(){
console.log("and appended event called in the same time");
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id='button'>click</button>
&#13;
&#13;
&#13;