Допустим, у меня есть этот HTML ...
<button class="btn-remove-this">Remove this</button>
<button class="btn-remove-that">Remove that</button>
<button class="btn-remove-some-other-thing">Remove some other thing</button>
<!-- and many more 'Remove ...' buttons -->
... и этот JavaScript.
$(function() {
$('.btn-remove-this').click(function() {
functionWhichRemovesThis();
}
$('.btn-remove-that').click(function() {
functionWhichRemovesThat();
}
$('.btn-remove-some-other-thing').click(function() {
functionWhichRemovesSomeOtherThing();
}
// and many more click handlers
});
Теперь я хотел бы предложить пользователю подтвердить диалог, прежде чем удалять все эти вещи. Есть ли способ сделать это без добавления и вызова confirm
внутри каждого отдельного обработчика кликов?
Я имею в виду что-то вроде добавления одного класса ко всем различным кнопкам (скажем, btn-remove
), а затем добавление обработчика одного клика, который может выглядеть следующим образом:
$('.btn-remove').click(function() {
if (confirm('Are you sure you want to remove this?')) {
// execute the body of the "more specific" click handler
} else {
// prevent the body of the "more specific" click handler from executing
}
}
3 ответа
Вы можете написать разные обработчики щелчков для разных кнопок, и функция общего вызова будет вызывать функцию, которую вы хотите вызвать, имеет параметр, и при обычном нажатии вы можете вызвать эту функцию обратного вызова.
$('.btn-remove-this').click(function() {
check(functionWhichRemovesThis);
});
$('.btn-remove-that').click(function() {
check(functionWhichRemovesThat);
});
$('.btn-remove-some-other-thing').click(function() {
check(functionWhichRemovesSomeOtherThing);
});
function check(callback){
if (confirm('Are you sure you want to remove this?')) {
callback();
} else {
// prevent the body of the "more specific" click handler from executing
}
}
Это тоже способ. Так что вам не нужно много менять свой код.
Я предлагаю вам использовать data-*
для этого здесь в вашем случае:
<button class="btn-remove" data-func="functionWhichRemovesThis">Remove this</button>
<button class="btn-remove" data-func="functionWhichRemovesThat">Remove that</button>
<button class="btn-remove" data-func="functionWhichRemovesSomeOtherThing">Remove some other thing</button>
Теперь в вашем коде JS вы можете сделать это:
var removeUtil = {
functionWhichRemovesThis : function(){},
functionWhichRemovesThat : function(){},
functionWhichRemovesSomeOtherThing : function(){}
};
$('.btn-remove').click(function() {
if (confirm('Are you sure you want to remove this?')) {
var removeIt = $(this).data('func');
removeUtil[removeIt];
}
});
Вот пример того, как я бы это сделал:
<button class="btn-remove btn-remove-some-other-thing">Remove something</button>
<button data-callback="App.remove.that" data-confirmText="Remove that?" class="btn-remove btn-remove-some-other-thing">Remove that</button>
<button data-callback="App.remove.this" data-confirmText="Remove this?" class="btn-remove btn-remove-some-other-thing">Remove this</button>
<script type="text/javascript">
var App = {};
App.remove = {};
// create an object to define different callbacks, outside of document(ready) so you an access it anywhere else you want.
App.remove['this'] = {
'yes': function () {
console.log('this.yes')
},
'no': function () {
console.log('this.no')
}
};
App.remove['that'] = {
'yes': function () {
console.log('that.yes')
},
'no': function () {
console.log('that.no')
}
};
$(document).ready(function () {
$('.btn-remove').click(function () {
var callback = {};
if (typeof $(this).attr('data-callback') !== 'undefined') {
// get the callback object of current button.
callback = $(this).attr('data-callback').split('.').reduce(function (obj, i) {
return App.remove[i];
}, App.remove);
}
var confirmText = 'Are you sure you want to remove this?';
if (typeof $(this).attr('data-confirmText') !== 'undefined') {
// set alternate text if needed
confirmText = $(this).attr('data-confirmText');
}
if (confirm(confirmText)) {
if (callback.hasOwnProperty('yes')) {
// do callback if property exists in callback object
callback.yes();
}
} else {
if (callback.hasOwnProperty('no')) {
// do callback if property exists in callback object
callback.no();
}
}
});
});
</script>
Похожие вопросы
Новые вопросы
javascript
По вопросам программирования на ECMAScript (JavaScript / JS) и его различных диалектах / реализациях (кроме ActionScript). Включите все соответствующие теги в свой вопрос; например, [node.js], [jquery], [json] и т. д.