jQuery在jsFiddle中工作,但在Drupal中不起作用

时间:2013-12-07 18:09:09

标签: javascript jquery html drupal

晚上好, 我对jQuery很新,所以如果我问一个愚蠢的问题,我希望你原谅我,但显然我一直面临着以下问题,我认为我自己无法解决。

我正在尝试实现jQuery代码来更改表的列顺序。代码如下:

$(document).ready(function (table, from, to) {
    var rows = jQuery('tr', table);
    var cols;
    rows.each(function () {
        cols = jQuery(this).children('th, td');
        cols.eq(from).detach().insertBefore(cols.eq(to));
    });
}(jQuery('#changeorder'), 1, 0));

它完美地工作在jsFiddle中有一个id为“changeorder”的表,但在Drupal网站上不起作用。我也尝试删除$(document).ready部分,并添加(jQuery);最后,结果相同。

我尝试将代码添加到html.tpl.php,就在包含jQuery javascript之后:

<!-- jQuery library (served from Google) -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>

<script> 
$(document).ready(function (table, from, to) {
var rows = jQuery('tr', table);
var cols;
rows.each(function () {
cols = jQuery(this).children('th, td');
cols.eq(from).detach().insertBefore(cols.eq(to));
});}(jQuery('#changeorder'), 1, 0));
</script>

我还尝试使用drupal_add_js()将内容直接添加到我需要它的页面。仍然没有进展。

对我做错了什么的想法?

事先谢谢。

1 个答案:

答案 0 :(得分:3)

你应该将整个JS包装在(function($){})(jQuery)中; 然后使用你的$代替你的jQuery实例...... drupal总是喜欢这个对我好。

我还建议将其转换为一个函数,您可以在需要时调用它,而不是像现在一样直接将变量传递给文档。

(function ($) {

$(document).ready(function() {
  function tableChange(table, from, to){ 
    var rows = $('tr', table);
    var cols;
    rows.each(function () {
    cols = $(this).children('th, td');
    cols.eq(from).detach().insertBefore(cols.eq(to));
  };
  tableChange('#changeorder', 1, 0)
});

})(jQuery);

根据我的经验,drupal的最佳实践不应该将您的脚本添加到您的html.tpl中,而是应该添加到yourtheme.info文件中:

scripts[] = yourjsfiles/script.js

然后在script.js文件中,您可以使用以下内容:

(function ($, Drupal, window, document, undefined) {
    $(document).ready(function(){
    //your code here
    }); 
})(jQuery, Drupal, this, this.document);

您想尝试避免使.tpl文件混乱。从长远来看,你会感谢我这一点:)

编辑:我刚刚在你的问题中注意到包含jquery。这不能以您尝试的方式完成。默认情况下,Drupal 7使用jquery 1.4.4,更新它的方法是jQuery Update Module