为什么这个.click()不会像.hover()一样工作?

时间:2013-12-03 13:02:35

标签: javascript jquery css

这有效:

$("a.hover").hover(function (){
        $(this).css("text-decoration", "underline");
    },function(){
        $(this).css("text-decoration", "none");
    }
);

这不是:

$("a.click").click(function (){
        $(this).css("text-decoration", "underline");
    },function(){
        $(this).css("text-decoration", "none");
    }
);

我知道它可能不是这样设计的,但为什么不呢?

我也不完全确定在逗号实际执行后有第二个功能。我只是这样写的:

$("a.click").click(function (){
        $(this).css("text-decoration", "underline");
    });

http://jsfiddle.net/tmyie/4DygF/7/

任何澄清都会很棒。

7 个答案:

答案 0 :(得分:4)

.click()注册表是目标元素集的点击处理程序,hover()是注册mouseentermouseleave处理程序的快捷方式。

hover

  

将两个处理程序绑定到匹配的元素,以便在执行时执行   鼠标指针进入并离开元素。

.click()使用.toggle()也有类似的短片,但它是removed in jQuery 1.9

目前,如果您想要相同的功能,可以查看this toggleClick() implemetation

答案 1 :(得分:0)

.hover()需要两次回调 - 一次用于悬停,另一次用于悬停。 .click()只应给出一个回调。既然你给它两个,它实际上认为第二个是点击回调。

答案 2 :(得分:0)

jQuery点击事件的定义,如http://api.jquery.com/click/所示:

.click( handler(eventObject) )

它需要一个参数,即触发click事件时要执行的函数。在您的示例中,您提供了两个函数作为click函数的参数。因此,这不会起作用。

答案 3 :(得分:0)

对于您可以使用的点击,如果/其他如此: 因为Click事件有1个回调函数

    var state=0;
    click(function(){
    if(state==0){
    //do this
    state=1;
    }
else{
    //do this
    state=0;
    }
    });

答案 4 :(得分:0)

你可以通过这样的方式让它发挥作用:

// listen for a.click to be clicked within the scope of the body
$('body').on('click', 'a.click', function(e){

    // prevent the click from registering
    e.preventDefault();

    // check if text-decoration is an underline
    if($(this).css('text-decoration').substring(0, 9) == 'underline'){
        // set it to nothing
        $(this).css('text-decoration', 'none');
    }
    else{
        // set it to underline
        $(this).css('text-decoration', 'underline');
    }
});

答案 5 :(得分:0)

那是因为使用.hover你可以添加两个处理程序(handlerIn,handlerOut),但.click只有一个处理程序

答案 6 :(得分:0)

如果您希望click的行为与toggle相同。请尝试此操作:

var a=1;
$("a.click").click(function (){
if(a==1){
    $(this).css("text-decoration", "underline");
    a=0;
}else{
    $(this).css("text-decoration", "none");
    a=1;
}
});

Demo

相关问题