简体   繁体   English

jQuery的点击事件不触发按钮动作

[英]jquery click event not triggering button action

I am using JQuery and I have loaded a bunch of Javascript for a web page which works as expected. 我正在使用JQuery,并且已经为网页加载了许多Javascript,该网页可以按预期工作。 However when I try to add the following code to trigger a button click, the button is not activated. 但是,当我尝试添加以下代码来触发按钮单击时,该按钮未激活。

$(document).ready(function(){
    $('.add_link').click();
});

I am wondering what I am doing wrong? 我想知道我在做什么错? I have this bit of code in a separate file that gets loaded after all the other javascript files are loaded. 我在单独的文件中有这部分代码,在所有其他javascript文件加载后即被加载。 Any hints? 有什么提示吗?

Thanks. 谢谢。

$('.add_link').click();

Maybe the button is not found, because it does not have the specified class. 也许找不到该按钮,因为它没有指定的类。 Look for typos or maybe you just forgot to set the class for the button? 寻找拼写错误,或者您只是忘了设置按钮的类?

What should happen, when you click the button? 当您单击按钮时会发生什么?

What is the html code for this? 这是什么html代码?

I have found the answer after playing around some more. 我玩了更多之后找到了答案。 Since I am using Drupal, I need to use a closure to make sure it works correctly. 由于我使用的是Drupal,因此需要使用闭包来确保其正常工作。 The correct code should be: 正确的代码应为:

jQuery(document).ready(function($){
   $('.add_link').click();
});

It is always the small things that trip you up. 小事情总是使您绊倒。 Thanks for all the responses. 感谢您的所有回复。

HTML : HTML

<button class="add_link">Click ME</button>

Javascript : Javascript

$(document).ready(function(){
    $('.add_link').click(function(event){
        //I'm the event handler
        console.log(event);
        alert(".add_link clicked!!!");
    });
});

Other examples : 其他例子

$(document).ready(function(){
    //Named function
    function myHandle(event){
        //I'm the event handler
        console.log(event);
        alert(".add_link clicked!!!");
    }

    //adding event with event alias
    $(".add_link").click(myHandle);

    //adding event with jQuery.on
    $(".add_link").on("click", myHandle);

    //adding event with jQuery.on and delegation
    $("body").on("click", ".add_link", myHandle);

});

I use jQuery.on because syntax of delegation and simple event handling is almost the same. 我使用jQuery.on是因为委托的语法和简单的事件处理几乎相同。 jQuery.on is newer then jQuery.bind , jQuery.live and jQuery.delegate too. jQuery.on较新则jQuery.bindjQuery.livejQuery.delegate了。

jsFiddle jsFiddle

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM