最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - Drupal 7 global javascript variables - Stack Overflow

programmeradmin3浏览0评论

In my Drupal 7 installation, I have 2 separate JavaScript files that are loaded by my sub-themes (base and admin sub-theme) - I don't know if this is useful information or not, but:

What if I want to define a JavaScript variable in the first js file that is loaded and use it in the second one? How should I define it?

Basically, the question could be: How to define global JavaScript variables in a Drupal environment?

I am using jQuery.

Thanks in advance!

Edit:

First js file:

var myOwnVar;

(function ($) {
    $(document).ready(function() {
        myOwnVar = 1;
    });
}(jQuery));

Second js file:

(function ($) {
    $(document).ready(function() {
        console.log(myOwnVar);
    });
}(jQuery));

In my Drupal 7 installation, I have 2 separate JavaScript files that are loaded by my sub-themes (base and admin sub-theme) - I don't know if this is useful information or not, but:

What if I want to define a JavaScript variable in the first js file that is loaded and use it in the second one? How should I define it?

Basically, the question could be: How to define global JavaScript variables in a Drupal environment?

I am using jQuery.

Thanks in advance!

Edit:

First js file:

var myOwnVar;

(function ($) {
    $(document).ready(function() {
        myOwnVar = 1;
    });
}(jQuery));

Second js file:

(function ($) {
    $(document).ready(function() {
        console.log(myOwnVar);
    });
}(jQuery));
Share Improve this question edited Jan 9, 2013 at 13:01 MrUpsidown asked Jan 9, 2013 at 11:51 MrUpsidownMrUpsidown 22.5k15 gold badges83 silver badges141 bronze badges 1
  • did u find ans to this problem, I am having same issue – Hitesh Commented Nov 14, 2014 at 12:21
Add a ment  | 

1 Answer 1

Reset to default 6

You want to use Drupal.settings.

The values can be globally accessed across the JavaScript functions.

You can pass variables from your PHP to JS...

drupal_add_js(array('YOURMODULE' => array('SOMEVARIABLE' => 'woohoo')), 'setting');

Then access the variable in your JS function...

(function ($) {
  Drupal.behaviors.YOURMODULE = {
    attach: function (context, settings) {

      // You can access the variable by using Drupal.settings.SOMEVARIABLE
      alert(Drupal.settings.YOURMODULE.SOMEVARIABLE);

    }
  };
})(jQuery);

Please refer to http://drupal/node/172169#variablesandarrays

"Variables should not be defined in the global scope; try to define them in a local function scope at all costs. All variables should be declared at the beginning of a function."

Alternatively, the following outside of any closures will work but should be avoided.

var SOMEVARIABLE = SOMEVALUE;

(function ($) {
  Drupal.behaviors.YOURMODULE = {
发布评论

评论列表(0)

  1. 暂无评论