将jQuery构件添加到Drupal页面导致`$不是函数`

问题描述:

我试图在Drupal上添加一个datepicker构件到我的表单。

我有一个页面下面的代码:

<script> 
$(function() { 
    $("#datepicker").datepicker({ 
     changeMonth: true, 
     changeYear: true 
    }); 
}); 
</script> 
<form action="/scripts/new-customer.php"> 
<div>Birth date: <input type="text" id="datepicker" name="bday" /></div> 
</form> 

但不幸的是我得到了这个问题的错误。我试图写如下:

<script> 
    (function($) { 
     $("#datepicker").datepicker({ 
      changeMonth: true, 
      changeYear: true 
     }); 
    })(jQuery); 
</script> 

但是我得到了同样的错误行后。

不幸的是,我无法进一步了解Drupal文档。

+0

使用jQuery.conflict() – 2013-04-20 17:51:01

+0

有你包括jQuery和jQuery UI库? – Eli 2013-04-20 18:06:12

由于其他JavaScript库冲突。使用jQuery.noConflict()

var jq = jQuery.noConflict(); 

jq(function() { 
    jq("#datepicker").datepicker({ 
     changeMonth: true, 
     changeYear: true 
    }); 
}); 

前初始化

drupal_add_library('system','ui.datepicker') 
+0

相同的错误,但用'jq'代替:'TypeError:jq(...)。datepicker不是函数。 – Zagorax 2013-04-20 18:01:21

+0

你有没有包含jQuery UI库 – 2013-04-20 18:06:38

+0

是的,我有。 Drupal 7已经包含jQuery和jQuery UI。 – Zagorax 2013-04-20 18:08:52

Drupal可能使用jQuery's noConflict option。改为尝试jQuery("#datepicker").datepicker()

+0

不幸的是我得到'TypeError:jQuery(...)。datepicker不是一个函数'。 – Zagorax 2013-04-20 17:59:29

不知道,但,这可能帮助:

jQuery(function($) { 
    $("#datepicker").datepicker({ 
    changeMonth: true, 
    changeYear: true 
    }); 
}); 

为了避免与其他JS库 “$” 不会使现场冲突在全球的.js文件中。 所以,你应该添加以下代码周围的js代码:

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

$('selector').mouseover(function() { 
//now working 
}); 

} 
}; 
})(jQuery); 
+0

这不是forooooooooooooo !!!! – MLSC 2014-01-27 14:10:05

正如泰米尔建议,下面的代码工作得很好:

<head> 
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/south-street/jquery-ui.css"> 
<script src="//code.jquery.com/jquery-1.10.2.js"></script> 
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script> 
<script type="text/javascript" src="api/jquery.ui.datepicker-it.js"></script> 
<?php drupal_add_library('system','ui.datepicker') ?> 
<script> 
    var jq = jQuery.noConflict(); 
    jq(function() { 
     jq.datepicker.setDefaults(jq.datepicker.regional['it']); 
     jq("#giornoSel").datepicker(
      { 
       dateFormat: 'dd/mm/yy', 
       altField: '#giorno', 
       altFormat: 'yy-mm-dd', 
       showButtonPanel: true 
      } 
     ); 
    }); 
</script>