Use JavaScript variable as function name?

前端 未结 5 1055
抹茶落季
抹茶落季 2020-12-02 00:23

I have the following code in Javascript:

jQuery(document).ready(function(){
    var actions = new Object();
    var actions;
    actions[0] = \'create\';
            


        
5条回答
  •  一向
    一向 (楼主)
    2020-12-02 00:41

    I think you're trying to do something that you don't need to do in JavaScript. In PHP, function passing is a bit of a kludge. In JavaScript it is elegant and painless.

    How are you planning on calling these functions later? I'm guessing that you have these function names hard-coded into your HTML in the 'onclick' attributes. Hard-coding JavaScript into your HTML via the on* attributes is a bad idea. If that's what you're doing, you have to create variables in the global scope (another practice best avoided). In the browser, the global object is window. If you define a property on window, the function will be available globally:

    $(document).ready(function() {
      var myNames = [
        'create',
        'destroy'
      ];
      for (var i = 0; i < myNames.length; i++) {
        window[myNames[i] + 'Dialog'] = function() {
          alert('Hello');
        };
      }
    });
    

    This assumes that you have onclick attributes in your HTML that match up with the function names you're creating.

    A better way to do this would be to just create the functions as you bind them to the events, never even assigning them to variables:

    $(document).ready(function() {
      $('#createdialog, #destroydialog').each(function() {
        $(this).click(function() {
          alert('Hello');
        });
      });
    });
    

    This will make both your JavaScript and your HTML smaller and cleaner.

提交回复
热议问题