jQuery点击事件触发程序 [英] jQuery click event when triggered programatically

查看:115
本文介绍了jQuery点击事件触发程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个内联onclick事件的链接:

 < a href =#onclick =somefunction );>点击< / A> 

我在onclick事件上注册了一个附加功能:



$ pre> jQuery(#addMoreOptions)。live('click',function(){
console.log('clicked');
}) ;

当我点击浏览器上的链接,而不是当我以编程方式进行模拟时, / p>

  jQuery(#addMoreOptions)。 

程式化版本触发内联事件,但不触发活动事件。



当事件附加多个函数时,它使用什么顺序?

解决方案

我很确定这是事情发生的顺序引起的。



如果你看看这个实例,你会看到一切正常工作。这是因为事件已注册,然后调用。代码如下:

  jQuery(document).ready(function(){

jQuery #addMoreOptions)。live('click',function(){
console.log('clicked');
});

$('#addMoreOptions' ).click();

});

function somefunction()
{
alert(clicked);
}

当页面加载时,您会收到 alert 和一个 console.log



现在,将 $('#addMoreOptions')。click(); 在注册事件之前,如这个实例,你只能从内联函数中获得 alert



代码是

  jQuery(document).ready(function(){
$('#addMoreOptions' ();

jQuery(#addMoreOptions)。live('click',function(){
console.log('clicked');
});

});

function somefunction()
{
alert(clicked);
}


I have a link with an inline onclick event:

<a href="#" onclick="somefunction();">click</a>

I registered an additional function on the onclick event:

jQuery("#addMoreOptions").live('click',function(){
        console.log('clicked');
    });

Which works fine when I click on the link on the browser, but not when I simulate programmatically:

jQuery("#addMoreOptions").click();

The programatical version triggers the inline event but not the "live" one.

When you have multiple functions attached to an event, what order does it use?

解决方案

I am pretty sure this is caused by the order of things happening.

If you look at this live example you'll see everything works as expected. This is because the event is registered, and then called. The code looks like:

jQuery(document).ready(function(){   

    jQuery("#addMoreOptions").live('click',function(){
        console.log('clicked');
    });

     $('#addMoreOptions').click();      

});

function somefunction()
{
 alert("clicked");   
}

When the page loads, you get an alert and a console.log.

Now with the very small change of putting the $('#addMoreOptions').click(); before registering the event as in this live example you only get the alert from the inline function.

For reference the code is

jQuery(document).ready(function(){   
     $('#addMoreOptions').click();  

    jQuery("#addMoreOptions").live('click',function(){
        console.log('clicked');
    });   

});

function somefunction()
{
 alert("clicked");   
}

这篇关于jQuery点击事件触发程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆