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

HTML

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

Js

 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