JQuery将一个变量从函数传递给函数

时间:2013-08-23 15:31:18

标签: jquery function parameter-passing

我有一个通过.click函数检索的变量,我想将它传递给另一个函数,但我无法正确传递它,因为当我调用其他函数时没有任何反应。

var className;
var flavor;
(function ($) {

  Drupal.myTest = Drupal.myTest|| {};

  Drupal.behaviors.myTest= {

    attach: function (context, settings) {

          Drupal.myTest.myFunction= function (className) {
            var passedVar= className;
            alert(passedVar);
          };



          $('.buttons').on('click', function(event) {
            className = $(this).attr('class');
          });

          $('#test').on('click, function(event) {
        Drupal.myTest.myFunction();
          });

    }

  };

}(jQuery));

2 个答案:

答案 0 :(得分:1)

尝试

(function ($) {
    var className;
    var flavor;

    Drupal.myTest = Drupal.myTest|| {};

    Drupal.behaviors.myTest = {
        attach: function (context, settings) {
            Drupal.myTest.myFunction= function (className) {
                var passedVar= className;
                alert(passedVar);
            };

            $('.buttons').on('click', function(event) {
                className = $(this).attr('class');
            });

            $('#test').on('click', function(event) {
                Drupal.myTest.myFunction(className);
            });
        }
    };

}(jQuery));

答案 1 :(得分:0)

$(document).ready()

之外声明该函数
<script type="text/javascript">
    var myPassedVar;

    $(document).ready(function() {
        $('.buttons).click(function() {
          var className = $(this).attr(class);
        });

        myFunction = function (className) {
          myPassedVar = className;
          alert(myPassedVar);
        };

        $('#test').click(function() {
          myFunction(className);
        }
    }); //END $(document).ready()
</script>