Intermittent problem with Uncaught TypeError: Can not read property 'locac' of undefined

0

I'm having this problem

  

Uncaught TypeError: Can not read property 'locac' of undefined

With the code:

function fnc(){    
    var evt = (window.event ? window.event : event);
    var elemento = evt.target;
    var params = $(elemento).data('params');
    alert(params.locac);
}

$('body').on('click','button.inst',fnc);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><buttontype="button" data-params='{"locac":"reg","titulo":"Inserir Registro"}' class="btn btn-success inst">Inserir</button>

Sample link: example

But not always the error occurs, there is time that I click the button several times and it does not give this error, but there are times that I click once and it already gives error.

Sometimes it gives error and does not give error.

The error I only see in the real world

    
asked by anonymous 28.04.2015 / 16:17

1 answer

1

There are no apparent errors in your code, but I think the workaround is to put your script inside the ready event of jQuery. Read here .

Do this:

$(function () {
    function fnc(){    
        var evt = (window.event ? window.event : event);
        var elemento = evt.target;
        var params = $(elemento).data('params');
        alert(params.locac);
    }

    $('body').on('click','button.inst',fnc);
});

It's a good practice to always use this pattern when you need to manipulate the DOM.

    
30.04.2015 / 03:19