//MAIN HEADER - When looking Away From Field, "Disables" The Field
$("#main_form").on("focusout", "#main_header", disableField);
//MAIN HEADER - When Clicking On The Field, Returns It To Editing Mode
$("#main_form").on("click", "#main_header", enableField);
有没有办法重构这个,所以我使用单个函数,只是在我沿着页面添加变量?这种情况持续了大约15个元素
答案 0 :(得分:2)
这样的事可能吗?如果我理解正确
$("#main_form").on("click","input",function(){
$(this).enable() //or something?
})
$("#main_form").on("focusout","input",function(){
$(this).disable() //or something?
})
答案 1 :(得分:2)
您可以将对象传递给.on
,如event : function
:
$("#main_form").on({
focusout : disableField,
click : enableField
}, "#main_header");
答案 2 :(得分:1)
当然,我建议:
$("#main_form").on("focusout click", "#main_header", function(e){
switch (e.type) {
case 'focusout':
disableField();
break;
case 'click':
enableField();
break;
}
});
稍微减少代码:
var eventHandlingMap = {
'focusout' : disableField,
'click' : enableField
}
$('#main_form').on('focusout click', '.classOfElementsToActUpon', function(e){
// will call the appropriate function:
eventHandlingMap[e.type]();
// 'this' will be the element acted upon:
$(this).css('color', 'green'); /* or whatever... */
});
答案 3 :(得分:1)
function setFocusAndClick(arrayOfIds) {
$.each(arrayOfIds, function(i,v) {
$('#' + v).on('focusout', $('#' + v), disableField);
$('#' + v).on('click', $('#' + v), enableField);
});
}
setFocusAndClick({'main_form', 'second_form'});
答案 4 :(得分:0)
您不需要重构现有方法来减少代码重复。重构与此无关。
你可以把你的逻辑包装成一个函数,就像这样:
function handleEvent(callbacks, selector) {
$("#main_form").on(callbacks, selector);
}
// And then
handleEvent({
focusout : disableField,
click : enableField
}, "#main_header")