Reputation: 2806
I have a question about jquery onclick
function, the question is not bug;
when i write some button click functions that use jquery, i have write a lot of jquery, for example:
$(document).ready(function(){
$('#dp1').datepicker({
format: 'yyyy-mm-dd'
});
$('#dp2').datepicker({
format: 'yyyy-mm-dd'
});
$("#addNewQ").on('click', function(){
.......
});
$('#addNew').on('click', function(){
.......
});
$('#addText').on('click', function(){
.......
});
});
My question is how to write this better. I don't want to write a lot of click functions.
I have try to google, but I don't know the keyword. Thanks !
Upvotes: 1
Views: 68
Reputation: 103348
If these click events are running the same function, then you could give a class to multiple elements, and use that. For example, your date pickers could have class="datepicker"
added to them, which will just then require the 1 event listener:
$('.datepicker').datepicker({
format: 'yyyy-mm-dd'
});
However if each of these click events will run a different function, then you are best to have a different click event listener for each.
However, this doesn't mean you must list your click event listeners in 1 long DOM ready function. You can use Javascript OOP to better organise your click events.
You may find this article referring to Javascript OOP has some use for you:
http://net.tutsplus.com/tutorials/javascript-ajax/the-basics-of-object-oriented-javascript/
Upvotes: 2