简体   繁体   中英

Plain JS version for the jQuery code

I have the following jQuery code (I have changed names of div and functions, not going to make much difference)

$(function(){
    $('#div1').bind('touchend',function(){
        function1();
        function2();
    });
});

$(function(){
    $('#div2').bind('touchend',function(){
        function1();
        function3();
    });
});

This is the plain JS version of it, which doesn't work.

document.getElementById('div1').addEventListener('touchend',function(){
    function1();
    function2();
},false);

document.getElementById('div2').addEventListener('touchend',function(){
    function1();
    function3();
},false);

If someone can explain what is the meaning of the jQuery version first, and then point out what mistake I made with the plain js version, I'll be grateful!

[In case if you're wondering why am I doing this, I need to remove jQuery from the phonegap app I'm building, so that the page loads faster :-)]

Your code should work in any browser/DOM that supports touch events . The only thing I can figure here is that you miss the DOMContentLoaded event to invoke and therefore, try to get/query elements which are not ready yet.

So you should wrap your code into

document.addEventListener('DOMContentLoaded', function () {
}, false);

jQuery automatically does this for you, when you invoke $(function() {}); . If you pass a function into $() its a shortcut for $(document).ready(fnc)

The code does exactly what yours is doing, just keeping the handlers separate, I think the only trouble you had was the lack of using

document.addEventListener('DOMContentLoaded', function () {

Which means the dom wasn't ready and getElementById would not find anything.

Okay, I read few other posts here, and this one pretty much nailed it.

document.addEventListener('DOMContentLoaded', function () {
                      var div1 = document.getElementById('div1');
                      var div2 = document.getElementById('div2');
                      // event handler
                      var handler = function (event) {
                        function1();
                        function2();
                      };
                      var handler2 = function(event) {
                        function1();
                        function3();
                      };
                      // Bind the events
                      div1.addEventListener('touchend', handler, false);
                      div2.addEventListener('touchend',handler2,false);
                      }, false);

But if some one could explain me what is the flow and how the code works, my day is made :-)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM