JQuery onclick registration error

I have a button to which I want to connect a click listener, but every time the code starts, it gives a console error

jquery.js:4435 Uncaught TypeError: ((n.event.special[g.origType] || (intermediate value)).handle || g.handler).apply is not a function

Here the js code that triggers the error, the first line works fine, the second line causes an error

 $toolbar.off('click', '.btn-save'); // $toolbar is assigned $("#toolbar") on init $toolbar.on('click', '.btn-save', function(e){ saveData(0); }); 

What bothers me, if I run this bit of code manually through the console, I get no errors

Here is the HTML

 <div class="row" id="toolbar"> <div class="col-lg-12"> <button type="button" class="btn btn-primary btn-save">Save</button> <button type="button" id="btnCancel" class="btn btn-default btn-cancel">Cancel</button> </div> </div> 
+5
source share
4 answers

I found the problem below my listeners, there is an unrelated listener that I attached

$(document).on("click", "#btn-back", Views.Editor.close);

The problem here is that Views.Editor.close is the wrong method name. When I change the method name, the error will disappear

I did not understand that an unrelated listener could affect others.

+6
source

Oh. it looks like you might have the wrong jQuery options if I understood the question / what are you trying to do.

DOM events must be added to elements on

HTML:

 <div class="row"> <div class="col-lg-12"> <button id="save-btn-id" type="button" class="btn btn-primary btn-save">Save</button> <button type="button" id="btnCancel" class="btn btn-default btn-cancel">Cancel</button> </div> </div> 

JS:

 $(document).ready(function() { $('#save-btn-id').click(function(evt) { saveData(0); }); }); 
0
source

Try the following: https://jsfiddle.net/jorge182/a1y9abcj/2/

 toolbar = $("#toolbar") $(toolbar).off('click', '.btn-save'); // $toolbar is assigned $("#toolbar") on init $(toolbar).on('click', '.btn-save', function(e){ saveData(); }); function saveData(){ alert(); } 
0
source

From what I see in the jQuery API docs for my .off () function and in the above code example, it looks like the function is not passed as the third parameter to the .off () function. Thus, it is possible that the jQuery library complains that it cannot find a function to remove it.

See: http://api.jquery.com/off/

Try this and see if it helps:

 function clickListener(e){ saveData(0); }; $toolbar.off('click', '.btn-save', clickListener); $toolbar.on('click', '.btn-save', clickListener); 
0
source

Source: https://habr.com/ru/post/1245713/


All Articles