Click event also fires focus event causing a function to run twice - jQuery
I know this is probably a simple problem but I can't seem to find anything about it. I have the following code:
var moreitemsdiv = $('.moreitemsdiv');
$('.moreitemsanchor').bind("focus click", function(){
showList(this);
return false
});
function showList(this_anchor){
var thismoreitemsdiv = $(this_anchor).next(moreitemsdiv);
if ($(thismoreitemsdiv).hasClass('focus')) {
$(thismoreitemsdiv).removeClass('focus');
} else {
$(moreitemsdiv).removeClass('focus');
$(thismoreitemsdiv).addClass('focus');
}
};
The 'focus' class is added on the click but as the click is also a focus, it then removes it as it runs the function again. Do I need to unbind and then re-bind or开发者_如何学Python something?
Any help would be great, cheers!
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="Scripts/jquery-1.7.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
var moreitemsdiv = $('.moreitemsdiv');
// $('.moreitemsanchor').bind('focus', function (e) {
// showList($(this));
// });
// function showList(this_anchor) {
// var thismoreitemsdiv = this_anchor.next(moreitemsdiv);
// if (thismoreitemsdiv.hasClass('focus')) {
// thismoreitemsdiv.removeClass('focus');
// } else {
// moreitemsdiv.removeClass('focus');
// thismoreitemsdiv.addClass('focus');
// }
// };
$('.moreitemsanchor').bind('focus', function (e) {
var obj = $(this);
$('.moreitemsanchor').removeClass('focus');
obj.addClass('focus');
});
});
</script>
<style type="text/css">
.focus
{
border-color: Green;
}
</style>
</head>
<body>
<input type="text" class="moreitemsanchor" value="a" />
<input type="text" class="moreitemsanchor" value="b" />
<input type="text" class="moreitemsanchor" value="c" />
<input type="text" class="moreitemsanchor" value="d" />
</body>
</html>
精彩评论