晚上好, 我对 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() 将内容直接添加到我需要的页面。仍然没有任何进展。
知道我做错了什么吗?
先谢谢了。
最佳答案
您应该将整个 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
关于javascript - jQuery 可以在 jsFiddle 中使用,但不能在 Drupal 中使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20444733/