问题
A couple of weeks ago I was working on my project and wrote some code to make a table row clickable (been there, done that). This code had been used before without a problem. A day was wasted trying to get the code to work (even though I had done it multiple times before) - some of the things I tried to get it working were a - change id to class on everything, b - move code from bottom of script section to top, c - rename variables, d - add 'var' in front of variables, subtract var from in front of variables, e - change all single quotes to double quotes, change all double quotes to single quotes, f - change the name of the table, g - try to click the table instead of the row, h - put the table in a div, take the table out of a div, etc etc etc.
Nothing was successful, so as a last resort, late at night, I switched the .click to .on(click - and surprise surprise - everything worked fine.
The same thing happened yesterday, but instead of doing a - h , I jumped right to changing the .click to on(click.
Here are the two code snippets:
$("#mdtable tr").click(function() {
var localmdid = $(this).find("#mdid").html();
alert("mdid =" + localmdid);
});
$(document).on('click', '#mdtable tr', function(e) {
var localmdid = $(this).find("#mdid").html();
alert("mdid =" + localmdid);
});
The upper one NEVER works, the lower one ALWAYS works (I comment them in and out).
Here is a code snippet from another page that works just fine:
$("#patienttable tr").click(function() {
var passthis = $(this).find("#localid").html();
$.post("php/setsessionvariable.php",
{sessionval: passthis},
function(e) {window.location.href = "root.php"}
);
});
I've read the jQuery documentation and it says that the .click function is somehow directly related to the .on(click, and therefore to me, if one works, then other should work.
Being a noob, I would like to become a better programmer, and even though my code works with .on(click, I'd like to know why my .clicks don't work (an intellectual exercise).
So my questions are:
Are .click and .on(click really related?
Is there something obvious I'm missing in the click snippet that makes it non-functional?
Is there a different way to this about this issue?
Again, I thank you in advance
回答1:
The .click
will bind click event to elements that are present at that time in the DOM
whereas the on() will delegate the event and will bind the click (event) which are dynamically added later on.
Delegated events
Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, you can use delegated events to avoid the need to frequently attach and remove event handlers, Reference.
来源:https://stackoverflow.com/questions/17678496/jquery-click-not-working-jquery-onclick-working-fine