我正在尝试触发并自动点击a href
,如果它没有类.active
。我的目标是从myspace创建类似Tom的东西,以自动添加成员作为朋友。但是,如果按钮已被点击(has the class .active already)
,则此代码似乎会忽略,并且当我刷新页面时它会再次自动点击。这是我的代码
if ($(".follow-1:not(.active)")) {
jQuery(function(){
jQuery('.follow-1').click(SK_registerFollow(1));
});
} else {
// do nothing
}
我也试过了,但也没有成功:
if ($('.follow-1').hasClass("active")) {
// do nothing
} else {
jQuery(function(){
jQuery('.follow-1').click(SK_registerFollow(1));
});
}
------------- 更新 ---------------
HTML代码是:
<a class="follow-1" onclick="SK_registerFollow(1);">follow</a>
答案 0 :(得分:1)
好的,这里有很多错误,所以我会内联评论:
// $() 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
}
这是一个固定版本:
// 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
}
});
答案 1 :(得分:0)
if (!$('.follow-1').hasClass("active")) {
// do nothing
} else {
jQuery(function(){
jQuery('.follow-1').click(SK_registerFollow(1));
});
}
使用不等于运算符并尝试。
答案 2 :(得分:0)