1

ユーザーが入力ボックス (フォーカス) 内をクリックしたときに "myfunction" と呼ばれる関数を実行するコードは何ですか。

jquery で例を見たことがありますが、ストレートな JavaScript でそれを行う方法がわかりません。

4

3 に答える 3

3
var addEvent = (function(){
  /// addEventListener works for all modern browsers
  if ( window.addEventListener ) {
    /// I'm returning a closure after the choice on which method to use
    /// has been made, so as not to waste time doing it for each event added.
    return function(elm, eventName, listener, useCapture){
      return elm.addEventListener(eventName,listener,useCapture||false);
    };
  }
  /// attachEvent works for Internet Explorer
  else if ( window.attachEvent ) {
    return function(elm, eventName, listener){
      /// IE expects the eventName to be onclick, onfocus, onkeydown (and so on)
      /// rather than just click, focus, keydown as the other browsers do.
      return elm.attachEvent('on'+eventName,listener);
    };
  }
})();

上記のクロスブラウザ機能を使用すると、次のことができます (dom が完全にロードされたら):

addEvent(document.getElementById('your_input'),'focus',function(e){
  var input = e.target || e.srcElement;
  alert('this input has gained focus!');
});
于 2012-11-04T00:42:12.907 に答える
3

onfocus 属性を使用する

<input type="text" onfocus="someFunc()">

<script>
  function someFunc(){

  }
</script>
于 2012-11-04T00:37:42.000 に答える
1
document.getElementById("elementId").addEventListener("focus",function(e){
 //Do Something here
});
于 2012-11-04T00:37:07.107 に答える