drupal_add_js() 可以加入權重值來控制他的呈現順序, 系統對於 javascript 主要區分三階層來控制與呈現:
- JS_LIBRARY: Any libraries, settings, or jQuery plugins.
- JS_DEFAULT: Any module-layer JavaScript.
- JS_THEME: Any theme-layer JavaScript
drupal_add_js('jQuery(document).ready(function () { alert("Hello!"); });', array('type' => 'inline', 'scope' => 'footer', 'weight' => 5))
2、在模組的 .info 檔內加入JavaScript
scripts[] = somescript.js
3、程式中加入 JavaScript
4、在程式中傳送 Javascript值 到 'Drupal.settings'drupal_add_js('http://example.com/example.js', 'external');
在 Javascript 內的變數運用如下:drupal_add_js(array('myModule' => array('key' => 'value')), 'setting')
5、覆載 JavaScript<script> if (Drupal.settings.myModule.key == value){ alert('Got it!'); } </script>
利用 hook_js_alter() 來異動其他模組的的 引用參照路徑. 下範例將原 jQuery 指向路徑移轉:
function hook_js_alter(&$javascript) { $javascript['misc/jquery.js']['data'] = drupal_get_path('module', 'jquery_update') . '/jquery.js'; // Swap out jQuery to use an updated version of the library }
6、JavaScript/CSS 資源庫
系統提供一個標準方式添加到資源庫. 如有 JavaScript, CSS 要作為系統資源庫, 可藉由模塊中實作hook_library()來達成添加,這樣自己或其他模組就可在自己的網頁中使用 #attached['library']或drupal_add_library()來使用這些資源. 下即是添加一組 js, css 檔並取名為 vertical-tabs:
function system_library() { ... // 垂直 Tabs. $libraries['vertical-tabs'] = array( 'title' => 'Vertical Tabs', 'website' => 'http://drupal.org/node/323112', 'version' => '1.0', 'js' => array( 'misc/vertical-tabs.js' => array(), ), 'css' => array( 'misc/vertical-tabs.css' => array(), ), ); ... return $libraries; }
透過 drupal_add_library() 來 vertical-tabs 資源:
function theme_vertical_tabs($variables) { $element = $variables['element']; // Add required JavaScript and Stylesheet. drupal_add_library('system', 'vertical-tabs'); return '<div class="vertical-tabs-panes">' . $element['#children'] . '</div>'; }
drupal_add_library() 是直接使用核心的 JavaScript 檔案, 而 drupal_add_js() 則是用非資源庫的 JavaScript 檔案.
7、BehaviorsBehavior handling has changed again in Drupal 7, with modules now required to explicitly define their attach handler, and optionally specify a detach handler.
Instead of the settings being a global object, settings are now passed to your handlers directly, after the context.
These changes, besides namespaced jQuery, mean basic module code should go from something like this in Drupal 7
from http://blog.csdn.net/for023/article/details/7955477(function ($) { Drupal.behaviors.exampleModule = { attach: function (context, settings) { $('.example', context).click(function () { $(this).next('ul').toggle('show'); }); } }; })(jQuery);