如何处理 DOM 元素?



我正在学习如何为我的Odoo 10插件编写自定义JavaScript。

我写了以下代码:

odoo.define('ioio.io', function(require) {
'use strict'
const e = $('div.o_sub_menu_footer')
console.log('--testing--'.repeat(7))
console.log(e)
// the "Powered by Odoo" down the secondary menu
e.remove()
})

代码加载良好,我可以在控制台中看到我的测试字符串。
但是,当此代码在目标div之前加载时,e空/尚未填充,因此不会删除其内容。
从控制台手动执行此操作是有效的。

我的问题是这样做的正确方法是什么?以及如何确切知道代码何时执行?

你可以

  • 将 HTML 代码放在文件中的脚本标记之前
  • 使用 jQuery $(document(.ready(...(;

将脚本放在<body>标签的底部,以确保 DOM 在尝试操作它之前呈现它。

这是一个特定于Odoo的问题,所以你应该使用Odoo标准的方式,即通过它的baseJS类。该类包含一个ready()方法,该方法完全符合您的要求。

在您的情况下,要使用该函数,您需要首先要求该类。然后你可以使用ready().

更新代码后,它应如下所示:

odoo.define('ioio.io', function(require) {
'use strict'
// require base class
var base = require('web_editor.base');
//use its ready method
base.ready().done(function () {
// put all the code you want to get loaded 
// once the DOM is loaded within this block
const e = $('div.o_sub_menu_footer')
console.log('--testing--'.repeat(7))
console.log(e)
// the "Powered by Odoo" down the secondary menu
e.remove()
});
})

虽然您接受的答案会导致相同的结果,但您可能希望将其更新为此答案,因为这是Odoo的方式。通常建议尽可能多地在Odoo框架内工作,并仅在真正需要时才进行自定义。(尽管由于文档不佳,很难了解Odoo已经提供了哪些功能。

最新更新