drupal_add_js

Хочешь помочь с переводом? Это очень просто и быстро. Лишь зарегистрируйся, и можешь тут же начать переводить.

includes/common.inc, строка 2070

Версии
5
drupal_add_js($data = NULL, $type = 'module', $scope = 'header', $defer = FALSE, $cache = TRUE)
6
drupal_add_js($data = NULL, $type = 'module', $scope = 'header', $defer = FALSE, $cache = TRUE, $preprocess = TRUE)

Добавляет JavaScript файл, настройки или код на страницу.

Действие этой функции меняется, в зависимости от параметров, с которыми она вызывается. В основном она служит для добавления кода JavaScript на страницу, как в виде ссылки на существующий файл или как участок кода прямо на странице. С помощью этой функции можно осуществить следующие действия:

  • Добавить файл ('core', 'module' и 'theme'): добавляет ссылку на JavaScript файл на страницу. JavaScript файлы распологаются в определённом порядке, первыми идут 'core', затем 'module', и, наконец, 'theme'. Так что файлы добавленные позже легко могут заменить те, что добавлены раньше.
  • Добавить JavaScript код ('inline'): выполняет кусок JavaScript кода помещяя его прямо на страницу. Это может, например, быть полезным, когда следует сказать пользователю о приходе нового сообщения, alert окном, и т. д.
  • Добавить настройки ('setting'): Добавляет настройку для глобального хранилища JavaScript-настроек Drupal'а. Настройки для одной страницы необходимы некоторым модулям для соотвествующего функционирования. Настройки будут доступны через Drupal.settings.

Параметры

$data (необязателен). Если указывается, значение зависит от параметра $type:

  • 'core', 'module' или 'theme': Путь к файлу относительно base_path().
  • 'inline': JavaScript код.
  • 'setting': ассоциативный массив с настройками. Он помещается прямо в Drupal.settings. Вы можете захотеть поместить свои настройки в другую переменную для избежания засорения Drupal.settings.
$type (optional) The type of JavaScript that should be added to the page. Allowed values are 'core', 'module', 'theme', 'inline' and 'setting'. You can, however, specify any value. It is treated as a reference to a JavaScript file. Defaults to 'module'.

$scope (optional) The location in which you want to place the script. Possible values are 'header' and 'footer' by default. If your theme implements different locations, however, you can also use these.

$defer (optional) If set to TRUE, the defer attribute is set on the <script> tag. Defaults to FALSE. This parameter is not used with $type == 'setting'.

$cache (optional) If set to FALSE, the JavaScript file is loaded anew on every page call, that means, it is not cached. Defaults to TRUE. Used only when $type references a JavaScript file.

$preprocess (optional) Should this JS file be aggregated if this feature has been turned on under the performance section?

Возвращаемое значение

If the first parameter is NULL, the JavaScript array that has been built so far for $scope is returned. If the first three parameters are NULL, an array with all scopes is returned.

▾ 26 функции вызывают drupal_add_js()

color_scheme_form in modules/color/color.module
Конструктор формы. Возвращает форму конфигурирования.
comment_form in modules/comment/comment.module
Создаёт базовую форму для комментирования, которая будет добавлена к странице с нодой или отображена на отдельной странице.
drupal_add_tabledrag in includes/common.inc
Assist in adding the tableDrag JavaScript behavior to a themed table.
drupal_get_js in includes/common.inc
Returns a themed presentation of all JavaScript code for the current page.
form_expand_ahah in includes/form.inc
Add AHAH information about a form element to the page to communicate with javascript. If #ahah[path] is set on an element, this additional javascript is added to the page header to attach the AHAH behaviors. See ahah.js for more information.
install_tasks in ./install.php
Tasks performed after the database is initialized.
locale_update_js_files in modules/locale/locale.module
Update JavaScript translation file, if required, and add it to the page.
node_filter_form in modules/node/node.admin.inc
Return form for node administration filters.
openid_form_alter in modules/openid/openid.module
Implementation of hook_form_alter : adds OpenID login to the login forms.
system_clean_url_settings in modules/system/system.admin.inc
Form builder; Configure Clean URL settings. See alsosystem_settings_form()
system_date_time_settings in modules/system/system.admin.inc
Form builder; Configure the site date and time settings. See alsosystem_settings_form()
theme_fieldset in includes/form.inc
Форматирует группу элементов формы
theme_poll_choices in modules/poll/poll.module
Theme the admin poll form for choices.
theme_profile_admin_overview in modules/profile/profile.admin.inc
Theme the profile field overview into a drag and drop enabled table. See alsoprofile_admin_overview()
theme_table in includes/theme.inc
Возвращает темизированную таблицу.
theme_table_select_header_cell in includes/theme.inc
Возвращает ячейку заголовка для таблиц, имеющих функцию "Выделить все".
theme_taxonomy_overview_terms in modules/taxonomy/taxonomy.admin.inc
Темизирует обзор терминов как сортируемый список.
theme_textarea in includes/form.inc
Форматирует многострочное текстовое поле ввода для формы.
theme_textfield in includes/form.inc
Форматирует однострочное текстовое поле ввода.
user_admin_settings in modules/user/user.admin.inc
Form builder; Configure user settings for this site. See alsosystem_settings_form()
user_filter_form in modules/user/user.admin.inc
Form builder; Return form for user administration filters. See alsouser_filter_form_submit()
user_register in modules/user/user.module
Конструктор формы; Форма регистрации пользователя.
_batch_progress_page_js in includes/batch.inc
Batch processing page with JavaScript support.
_book_add_form_elements in modules/book/book.module
Build the common elements of the book form for the node and outline forms.
_init_theme in includes/theme.inc
Initialize the theme system given already loaded information. This function is useful to initialize a theme when no database is present.
_user_password_dynamic_validation in modules/user/user.module
Add javascript and string translations for dynamic password validation (strength and confirmation checking).

Код

<?php
function drupal_add_js($data = NULL, $type = 'module', $scope = 'header', $defer = FALSE, $cache = TRUE, $preprocess = TRUE) {
  static $javascript = array();

  if (isset($data)) {

    // Add jquery.js and drupal.js, as well as the basePath setting, the
    // first time a Javascript file is added.
    if (empty($javascript)) {
      $javascript['header'] = array(
        'core' => array(
          'misc/jquery.js' => array('cache' => TRUE, 'defer' => FALSE, 'preprocess' => TRUE),
          'misc/drupal.js' => array('cache' => TRUE, 'defer' => FALSE, 'preprocess' => TRUE),
        ),
        'module' => array(),
        'theme' => array(),
        'setting' => array(
          array('basePath' => base_path()),
        ),
        'inline' => array(),
      );
    }

    if (isset($scope) && !isset($javascript[$scope])) {
      $javascript[$scope] = array('core' => array(), 'module' => array(), 'theme' => array(), 'setting' => array(), 'inline' => array());
    }

    if (isset($type) && isset($scope) && !isset($javascript[$scope][$type])) {
      $javascript[$scope][$type] = array();
    }

    switch ($type) {
      case 'setting':
        $javascript[$scope][$type][] = $data;
        break;
      case 'inline':
        $javascript[$scope][$type][] = array('code' => $data, 'defer' => $defer);
        break;
      default:
        // If cache is FALSE, don't preprocess the JS file.
        $javascript[$scope][$type][$data] = array('cache' => $cache, 'defer' => $defer, 'preprocess' => (!$cache ? FALSE : $preprocess));
    }
  }

  if (isset($scope)) {

    if (isset($javascript[$scope])) {
      return $javascript[$scope];
    }
    else {
      return array();
    }
  }
  else {
    return $javascript;
  }
}
?>
Войдите или зарегистрируйтесь, чтобы получить возможность отправлять комментарии

Вход в систему