自动单击按钮(如果没有类)

Auto click button if doesn't has class

本文关键字:如果没有 按钮 单击      更新时间:2023-09-26

如果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>

好的,这里有很多问题,所以我将内联评论:

// $() 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
    }
});

jsFiddle 演示

if (!$('.follow-1').hasClass("active")) {
    // do nothing
} else {
    jQuery(function(){
        jQuery('.follow-1').click(SK_registerFollow(1));
    });
}

使用不等于运算符并尝试。

试试这个

jQuery('.follow-1').not('.active').click(SK_registerFollow(1));

工作示例