无需单击即可立即执行onclick事件 [英] onclick event is executed immediately without clicking

查看:189
本文介绍了无需单击即可立即执行onclick事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理一些包含span元素的click事件的代码(这段代码是创建span的函数的一部分):

I'm working on some code that contains a click event for a span element (This piece of code is part of the function that creates the span):

$("span[class=addnewsqlwherevalue][id='" + opts.counters[3] + "']").click(
function(e) { ...});

它在定义之后立即执行,并且当我单击指定的span元素时也执行,尽管我只希望在单击该元素时执行它.

It is executed immediately after it is defined there and also when I click the specified span element although I only want it to be executed when I click on the element.

我也尝试过:

function clickSpan(e) {...} 
$("span[class=addnewsqlwherevalue][id='" + opts.counters[3] + "']").onclick = clickSpan;

在上述情况下,它永远不会执行.

In the above case it is executed never.

$("span[class=addnewsqlwherevalue][id='" + opts.counters[3] + "']").on('click', function(e) {...}); // same as the first approach

我看过类似的问题,但其中没有一个可行的解决方案.该代码不是我提供的,因此我可能会遗漏一些东西,但是我认为在onclick事件的代码中没有执行任何代码的原因(因为该函数在创建时就被准确地调用了).

I looked at similar questions but they didn't contain a solution that worked. This code is not from me, so I might miss something but I assume that nowhere in the code this onclick event is executed (because the function is called exactly when it is created).

请多多包涵,我是javascript的新手,我需要在一个大项目中找到几个错误.

Please bear with me, I'm new to javascript and I need to find several bugs in a big project.

推荐答案

已在问题注释中找到答案.这只是评论的复制/粘贴,可以正确关闭问题.

on()是定义事件的正确方法,并且无法自动执行.因此,我想使用.click().trigger('click')

on() is the right way to define the event and cannot be executed automatically. So I would ask to check if the click event is not invoked in another place in the code using .click() or .trigger('click')

这篇关于无需单击即可立即执行onclick事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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