Better way to bind event in jquery
I have a page where I have many controls and then I have a div element and have 10 asp buttons in that div element.
I want to bind mousehover event to only those buttons which are inside the div element.
Currently i m doing it like:
<script src="jquery-1.6.2.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#MangoPager_btn1").hover(mousehoverfunction);
$("#MangoPager_btn2").hover(mousehoverfunction);
$("#MangoPager_btn3").hover(mousehoverfunction);
$("#MangoPager_btn4").hover(mousehoverfunction);
$("#MangoPager_btn5").hover(mousehoverfunction);
$("#MangoPager_btn6").hover(mousehoverfunction);
$("#MangoPager_btn7").hover(mousehoverfunction);
$("#MangoPager_btn8").hover(mousehoverfunction);
$("#MangoPager_btn9").hover(mousehoverfunction);
$("#MangoPager_btn10").hover(mousehoverfunction);
});
</script>
Is there any way in jquery so that i can declare a list of button ids something li开发者_Python百科ke [MangoPager_btn10,MangoPager_btn2,MangoPager_btn3]
so that i don't have to do that for every single button id.
I tried with input
type but then it's applying the function for all input type objects not for buttons which are in the div
elemet.
Any other bettrer way to do it in jquery .... I
Try this:
$(function(){
$("[id^='MangoPager_btn']").hover(mousehoverfunction);
})
$('#DivElementId input').hover(mousehoverfunction);
You can simply give a class to the desired inputs:
$(".mouse-over").hover(mousehoverfunction);
or if you just have a few ids:
$("#MangoPager_btn1, #MangoPager_btn2, #MangoPager_btn3").hover(mousehoverfunction);
$("#MangoPager button").hover(mousehoverfunction);
Bind the function to the parent div and then all the buttons like this. Assuming MagoPager is the id of the parent div.
or
$("#MangoPager input[type=]").hover(mousehoverfunction);
try something like this:
$(".containerclass input[type=submit]").hover(mousehoverfunction);
this will bind the function to all buttons inside a container wit (css)class="containerclass"
I recommend using delegate: http://api.jquery.com/delegate/ because it will attach a handler to one or more events for all elements
In this cases I use filters http://api.jquery.com/filter/ with regexp
$("input").filter(function()
{
return /MangoPager_btn/.test(this.id)
}).hover(mousehoverfunction);
精彩评论