简体   繁体   中英

JQuery recognize string as function dynamically callback

I have a simple jquery function that I am trying to get ajax to run dynamically. The function works fine when called as such

function widget1() { 
    console.log("test");
}

$(function () {                 
  $('#thisbutton').bind('click', function() {
  var htmlString = $("#uid").html();
     $.ajax({
      type: "GET",
      url: "/getappobj",
      data: {id:htmlString},
      success: function(data) {
        widget1();
      }
    });
});});

but if I try to get the function called dynamically I get an error that the string is not a function

$(function () {                 
  $('#thisbutton').bind('click', function() {
  var htmlString = $("#uid").html();
     $.ajax({
      type: "GET",
      url: "/getappobj",
      data: {id:htmlString},
      success: function(data) {
        var findit = data[0].widget;//returns "widget1"
        findit();
      }
    });
});});

I have tried this every way that I can think of. Using jquery-1.9.1.min.js.

If widget1 is global, you can call window[findit]() to get the function from the window object by name.

You are trying to call a string as a function which of course won't work. You need to use the string to look-up the function to execute.

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