Hello dear users of the hashcode project! When creating a pop-up window for your site on jQuery, I ran into a problem - a certain function is required to close the window.

Ideally, I would like to do this:

<span class="close" onclick="close()" callback="funcname">Закрыть</span> function close() { //.... if ($(this).attr('callback')!="") { // Некий код который выполнит функцию funcname } } 

Already tried $ (this) .attr ('callback') (); Please tell me how this can be done, it seems to me in JS there is a function like: vipolnit ('funcname'); but I just can't find it.

3 answers 3

Alternatively, you can use eval

Here is a working example: jsFiddle


 <span class="close" data-callback="custom()">Click me!</span> 


 function custom() { alert('Callback works!') } $('.close').click( function(){ var callback = $(this).attr('data-callback') if (callback.length > 0) eval(callback) }) 
  • one
    the person asking such questions should not show examples using eval , it is a powerful tool, but they need to be used very carefully, knowing exactly when and why it is better than other means - Specter
  • Thank you. Everything worked out! Thank you very much! - GeneralProger2
  • In jquery, it would be good to use var callback = $ (this) .data ('callback') -
 var callbackHash = { 'funcname': function(){...} // целевая функция, которую необходимо выполнить // если их несколько - дописать в хэш }; function close() { //.... var funcName = $(this).attr('callback'); if (callbackHash[funcName]) { // Некий код который выполнит функцию funcname callbackHash[funcName](); } } 

    I'm sorry, maybe I didn’t understand something, but what’s stopping you from doing this:

     $("#Идентификатор_кнопки_закрытия").live("click", callback); .... function callback() { // что-то там } 
    • I will try to explain in a real-fictional situation (if I understood the author correctly). Suppose you have a popup window. When you click on close, it closes. And everything is fine .. until the boss bursts in and says that he has a brilliant idea: that when you close only the registration window, a parrot will pop up! Therefore, the author is faced with the task of expanding the functional for special cases - Yakovlev Andrey