2016-11-15 21 views
10

JavaScriptを使用して<input> HTML要素を作成しました。今度は、onblurイベントハンドラをこの要素に動的に追加したいと思います。しかし、私は関数に引数として作成された要素を渡すことができる方法を理解していません。ここに私のコードです:javascriptのイベントハンドラに要素を渡すには

element = document.createElement("input"); 
element.onblur = hello_function; 

上記のコードでは、要素が作成されていることがわかります。今、その要素をhello_functionに渡したいと思います。どうやってやるの?この無名関数のラッパーでhello_function呼び出しをラップし、this引数を提供することができます達成するために

function hello_function(element) { 
    alert(element); 
} 
+1

'hello_function.bind(要素)'。また、 '.onblur'の代わりに' .addEventListener'を使うことをお勧めします。 – Rajesh

+0

何も渡す必要はありませんか?すでに 'this'か' event.currentTarget'を介して 'hello_function'の中でその要素にアクセスできます。 – Bergi

答えて

8

element = document.createElement("input"); 
 
element.addEventListener('blur', function() { 
 
    hello_function(this); 
 
}); 
 
document.body.appendChild(element); 
 

 
function hello_function(element) { 
 
    console.log(element); 
 
}

はまたonblur以上addEventListenerの好ましい使用に注意してください。

+0

好奇心をそそらず、 'event'オブジェクトに' hello_function() 'の中でアクセスしたいのであれば、それはどのように渡されますか? – asprin

+1

@asprin additionalnalイベントパラメータをhello_function()およびaddEventListenerに追加します。デモhttps://jsfiddle.net/xp5we163/82/ – Alexis

+0

これは 'hello_function(event、this);'であり、宣言は 'function hello_function(evt、element){....}'でしょうか? – asprin

1

このようにしてください。私はにaddEventListenerを使用することをお勧め

1

var something="hello"; 
 
var element = document.createElement("input"); 
 
    element.addEventListener('blur' , function() 
 
          { 
 
    hello_function(something); 
 
    
 
    }) 
 
document.body.appendChild(element) 
 

 
function hello_function (element){ 
 
     alert(element); 
 
}
、関数に別の変数を渡しても、私はあなたがドキュメントに作成された要素を追加する必要があると思う、このような何か:

var elem = document.createElement("input"); 
if (elem) { 
    elem.addEventListener('blur', hello_function, false); 
} 
document.body.append(elem); 
function hello_function(element) { 
    alert(element); 
} 
関連する問題