onclick event is executed immediately without clicking

时光总嘲笑我的痴心妄想 提交于 2019-12-23 03:27:15

问题


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) { ...});

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.

I also tried:

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

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).

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


回答1:


Answer has been found in the question comment. Here is just a copy/paste of the comment to close the question properly.

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')



来源:https://stackoverflow.com/questions/20966687/onclick-event-is-executed-immediately-without-clicking

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!