How to override something in jQuery?
The HTML:
<a href='#' id='myLink1' class='areaLink 开发者_如何学编程activeArea' onClick="myFunction('1')">Click Me 1</a>
<a href='#' id='myLink2' class='areaLink activeArea' onClick="myFunction('2')">Click Me 2</a>
CSS:
.activeArea { font-weight: bold; }
I have the following code runny on document ready:
$(document).ready(function() {
$('a.areaLink').click(function() {
$('a.areaLink').removeClass('activeArea');
});
});
And this code inside the function that executes on the onClick event:
function myFunction(num) {
$('#myLink'+num).addClass('activeArea'); // !important
}
OK, so when the page initially loads, visually the links should look like this:
Click Me 1
Click Me 2When the user clicks on either link, that link should become bold like so:
Click Me 1
Click Me 2So how can I make this line within the function:
$('#myLink'+num).addClass('activeArea');
OVERIDE the code running on document ready?
Remove the inline onclick from your a
tags. You also do not need to have a function to reference the clicked link. Use $(this)
instead.
$('.areaLink').click(function() {
$(this).addClass('activeArea').siblings().removeClass('activeArea');
});
Check working example at http://jsfiddle.net/SVVJk/1/
Why don't you just remove the .removeClass()
from the jQuery click event?
function myFunction(num) {
$('a.areaLink').removeClass('activeArea');
$('#myLink' + num).addClass('activeArea'); // !important
}
Should work fine. on document ready only loads once.
Do you want it to be bold the next time the page is loaded for the user?
Also, I believe
$(this).addClass('activeArea');
Will work as well as the code you have there... you don't need to pass in a number and use this naming convention.
Change your html to this:
<a href='#' class='areaLink'>Click Me 1</a>
<a href='#' class='areaLink'>Click Me 2</a>
And this is all the JS you need:
$(document).ready(function() {
$('a.areaLink').bind('click', function(e) {
e.preventDefault();
var $this = $(this);
if($this.hasClass('activeArea'))
return;
$this.siblings().removeClass('activeArea');
$this.addClass('activeArea');
});
});
You could simplify it all by doing the following:
<a href='#' id='myLink1' class='areaLink'>Click Me 1</a>
<a href='#' id='myLink2' class='areaLink'>Click Me 2</a>
And in your script:
$('a.areaLink').click(function() {
$(this).addClass('activeArea');
$(this).siblings('.areaLink').removeClass('activeArea');
});
I would recommend doing something like this:
<a href='#' id='myLink1' class='areaLink activeArea clicker' onClick="myFunction('1')">Click Me 1</a>
<a href='#' id='myLink2' class='areaLink activeArea clicker' onClick="myFunction('2')">Click Me 2</a>
notice the clicker class i have added to both.
now use this code
$(".clicker").click(function(){
$(this).addClass("whatever_class_you_want_to_add");
});
This means you dont need to worry about the number, because it is already known by the target of $(this)
精彩评论