Home>

Tell us about the following two differences in the jQuery on method.

Applicable source code
<! DOCTYPE html>
<html>
<head>
<meta charset = "UTF-8">
<title>sample page</title>
<script src = "https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src = "sample01.js"></script>
<link rel = "stylesheet" href = "sample.css">
</head>
<body>
    <button>Change</button>
    <div>Test</div>
</body>
</html>

Below, when executed with a comment and when executed with a non-comment,
Although there was no difference in the results with this code,
What is the difference between writing these two on methods in general?
Please tell us if you have any suggestions or suggestions on how to use them properly.

I'm not sure how to write comments.
Is the code "execute a function when you click on a document's .change"?

・ sample01.js

$(function () {
    //$(document).on("click "," .change ", function (e) {
    $(". change"). on ("click", function (e) {
        $('# myid'). removeClass ('sample');
        $('# myid'). addClass ('sample2');
    });
});

・ sample.css

. sample {
    color: blue;
}
.sample2 {
    color: red;
}
  • Answer # 1

    $(document) .on ("click" ;,".change" ;, () =>{})is
    It also responds to clicks on added.changeelements that are not in the HTML when the code is executed.

    [jQuery: How do I add event listeners to elements that don't exist in the document tree? (On)-Build Insider]
    https://www.buildinsider.net/web/jqueryref/017

    [Understanding jQuery on event delegates-to-R]
    http://blog.webcreativepark.net/2013/12/01-215447.html

    [Try to understand jQuery's .on () again-not very new]