I'm trying to fire and auto click on a a href
if it doesn't has the class .active
. My goal is to create something like Tom from myspace to automatically add a member as a friend. But this code seems to ignore if the button is already clicked (has the class .active already)
and it auto clicks again when I refresh the page. here's my code
if ($(".follow-1:not(.active)")) {
jQuery(function(){
jQuery('.follow-1').click(SK_registerFollow(1));
});
} else {
// do nothing
}
I also tried this but it was not successful as well:
if ($('.follow-1').hasClass("active")) {
// do nothing
} else {
jQuery(function(){
jQuery('.follow-1').click(SK_registerFollow(1));
});
}
------------- UPDATED ---------------
The HTML code is this:
<a class="follow-1" onclick="SK_registerFollow(1);">follow</a>
OK there's quite a few things wrong here so I'll inline comment:
// $() will always return a function, so this will always fire
if ($(".follow-1:not(.active)")) {
// This is waiting for a document.ready, so you need to do this on the outside
/// of your code
jQuery(function(){
// This will execute SK_registerFollow immediately
// and send the result to your handler. Probably not what you want
jQuery('.follow-1').click(SK_registerFollow(1));
});
} else {
// No need to ever have a block which 'does nothing'
// do nothing
}
Here's a fixed version:
// Wait for DOM to become ready
$(function() {
// Store a reference to the link, so we don't need to search for it twice
var $follow = $(".follow-1");
// Test to see if the link has the active class
if (!$follow.hasClass("active")) {
$follow.click(); // This will trigger the appropriate onclick handler
}
});
if (!$('.follow-1').hasClass("active")) {
// do nothing
} else {
jQuery(function(){
jQuery('.follow-1').click(SK_registerFollow(1));
});
}
Use not equal to operator and try.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.