したがって、動的に追加された要素のイベントハンドラーを提供するjQueryの .on() 関数について知っています。
たとえば、私はこのように使用しました
$(document).on("change",Items,function(){/*Code here*/});
しかし、オブジェクトがドキュメントに追加されたら、この .on() 関数 (または他の何か) を使用して関数を呼び出す方法はありますか? より良い選択ボックスを作成するChosenと呼ばれるjqueryプラグインを使用しているため、これを尋ねます。
$(selector).chosen();
ただし、要素がドキュメントに追加される前にその行が使用された場合、その行は機能しません。また、コードをきれいにするために、要素が追加されたときにその行を実行する関数を呼び出すことができれば便利です。要素を追加した後にその行を追加する代わりに。
編集:問題は、要素を追加した後に .chosen() を使用できないことではありません。出来るからです!$(selector).chosen() 行がコードの一番下に隠されないようにすることで、コードをより適切に整理できるようにしたいだけです。
私のコード:
//Create the dropdown box for the items
var Items = document.createElement("select");
$(Items).attr( {"id":"Items"} );
$(document).on("change",Items,
function(){
updateHolder(true);
$(InfoBox).trigger("chosen:updated");
setTimeout(
function(){
$(Items).data('chosen').input_blur();
}, 100
);
}
);
//Add items from ED.listOfItems to HTML Items dropdown box
for(var it in ED.listOfItems){
var iKey = ED.listOfItems[it];
var itemOption = document.createElement("option");
if(!Array.isArray(iKey)){
$(itemOption).val(iKey);
$(itemOption).html(iKey.split("_")[0]);
}
else{
$(itemOption).val(iKey[0]);
$(itemOption).html(iKey[1]);
}
$(Items).append( itemOption );
}
/*******Set default to spawn*******/
/**/ ED.objectType = "Spawn"; /**/
/**/ ED.infoType = ""; /**/
/**/ $(Items).val("Spawn"); /**/
/**********************************/
$(MenuBar).append(Items);
$(Items).chosen({disable_search_threshold: 100});
$("#Items_chosen").css({"width":"100px","position":"absolute","left":"5px","top":"20px"});
ご覧のとおり、最後から 2 番目の行が選択された行ですが、私には非論理的な場所にあるようです。私は私のコードで非常にOCDです:P