JQuery click() 不工作

JQuery click() not working

这是最奇怪的事情:

$(document).ready(function() {

    $( ".selector" ).first().css( "background-color", "red" ); // This works
    $( ".selector" ).first().click();                          // This doesn't

    $( ".selector" ).click(function(e) {

        alert("plop");

    });
});

当然,当我单击 .selector 时,我确实看到了警报...是什么原因?

想想你做事的顺序:

//click the first .selector:
$( ".selector" ).first().click();                          
//from now on, when .selector is clicked, fire an alert
$( ".selector" ).click(function(e) {
    alert("plop");
});

如果你这样做:

//from now on, when .selector is clicked, fire an alert
$( ".selector" ).click(function(e) {
    alert("plop");
});
//click the first .selector:
$( ".selector" ).first().click(); 

它应该有效

在此之后您可能会捂脸,但您在添加点击处理程序之前调用了点击事件。您的代码是这样写的:

Click on the first .selector

If any .selectors get clicked on from now on, do this function

如果将 click 处理程序移动到 .click() 调用上方,它将正常工作。