2016-06-17 20 views
1

Ich bin daran interessiert, Onfocus oder andere ähnliche Funktionen zu einem DOM-Elemente in Laufzeit zuweisen.Zuweisen von Onfocus zu DOM-Elementen in Runtime

Allgemeiner Fall:

<input type="text" id="box" onfocus="inputFocused()"/> 

Runtime Zuordnung Fall:

<input type="text" id="box"/> 

Und im Skript

$('#box').onfocus = inputFocused(); 

inputFocused() ist nichts anderes als eine einfache Funktion. Es scheint nicht richtig zu funktionieren.

Danke für jede Hilfe.

Antwort

1

Man könnte es als verwenden:

$('#box').on('focus',inputFocused); 

Hoffnung, das hilft.

$('#box').on('focus',inputFocused); 
 

 
function inputFocused(){ 
 
    alert('focused'); 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<input type="text" id="box"/>

1

Ersetzen Sie einfach

$('#box').onfocus = inputFocused(); 

mit:

$('#box').focus(inputFocused); 

Es ist die jquery korrekte Syntax. Vom docs:

Diese Methode ist eine Abkürzung für .on ("Focus", handler) ...