在页面上包含两个版本的 jQuery,而不影响旧插件

2024-01-17

我们的 drupal 站点使用 jQuery 版本 1.2.1 运行,我们尚未升级该版本。

问题是这样的:

我们需要添加一个名为 jQuery Tokeninput 的新插件,但它仅适用于最新的 jQuery 版本。我们尝试将最新的 jQuery 版本添加到旧版本中,但它产生了奇怪的结果。

我的问题是,如何包含最新的 jQuery 文件而不影响旧的 jQuery 插件?


方法#1:(推荐)

你可以这样做:

<script type='text/javascript' src='js/jquery_1.7.1.js'></script>   
<script type='text/javascript'>  
 // In case you wonder why we pass the "true" parameter,
 // here is the explanation:
 //   - When you use jQuery.noConflict(), it deletes
 //     the "$" global variable.
 //   - When you use jQuery.noConflict(true), it also
 //     deletes the "jQuery" global variable.
 var $jq = jQuery.noConflict(true);  
</script>  
<script type='text/javascript' src='js/jquery_1.2.1.js'></script> 

这样当你想要用新版本的 jquery 而不是$ use $jq.

$jq('.selector').on('click', function(){  
    //do something  
});

方法#2:(可能会破坏您网站上的内容 - 不推荐)

In your template.php file:

<?php
function {theme_name}_preprocess(&$vars, $hook) {
if (arg(0) != 'admin' && $hook == "page") {
// Get an array of all JavaScripts that have been added
$javascript = drupal_add_js(NULL, NULL, 'header');

// Remove the original jQuery library
unset($javascript['core']['misc/jquery.js']);

// Add in our new jQuery library
// We do it this way to keep the includes in the same order
$core = array(
//Alternative jQuery
drupal_get_path('theme', '{theme_name}').'/js/libs/jquery-1.7.1.min.js' => array(
'cache' => TRUE,
'defer' => FALSE,
)
);

// Merge back into the array of core JavaScripts
$javascript['core'] = array_merge($javascript['core'], $core);

// Rerender the block of JavaScripts
$vars['scripts'] = drupal_get_js(NULL, $javascript);
}
}

请务必仅在网站的前端执行此操作。如果管理工具栏依赖于 Drupal 的 jQuery 版本,它可能会弄乱管理工具栏。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在页面上包含两个版本的 jQuery,而不影响旧插件 的相关文章