问题
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