You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Oracle JET面板展开/折叠报错:Uncaught TypeError问题求助

解决Oracle JET面板展开/折叠中的Uncaught TypeError问题

嘿,我一眼就看出你遇到的这个Uncaught TypeError: Cannot read property 'style' of null问题的根源了——你在ViewModel初始化阶段就直接去获取DOM元素(panel和extra-content),但这时候Oracle JET还没完成页面的DOM渲染和绑定工作,所以document.getElementById返回的是null,后续访问style自然就报错了。

具体解决方案

Oracle JET提供了组件生命周期函数,我们可以把DOM元素的获取逻辑移到connected函数里,这个函数会在组件成功挂载到DOM之后才被调用,这时候目标元素肯定已经存在了。同时要调整变量的作用域,让buttonClick方法能访问到这些元素。

修改后的JS代码如下:

define(['ojs/ojcore', 'knockout', 'jquery', 'ojs/ojknockout', 'promise', 'ojs/ojtable', 'ojs/ojarraytabledatasource','ojs/ojbutton', 'ojs/ojanimation'], 
function(oj, ko, $) {
  function CustomerViewModel() {
    var self = this;
    
    // 先声明变量,后续在connected中赋值
    self.panel = null;
    self.extra = null;
    self.initHeight = '';

    // Keep track of whether the element is expanded
    self.expanded = false;
    self.buttonIcons = ko.observable({end:'oj-panel-expand-icon'});
    self.buttonLabel = ko.observable('expand');

    self.buttonClick = function() {
      if (self.expanded) {
        // Call the collapse method, then hide the extra content when animation ends.
        oj.AnimationUtils['collapse'](self.panel, {'endMaxHeight': self.initHeight}).then(function() {
          self.extra.style.display = 'none';
          self.expanded = false;
          self.buttonIcons({end:'oj-panel-expand-icon'});
          self.buttonLabel('expand');
        });
      } else {
        // Mark the extra content to be displayed, followed by a call to the expand method.
        self.extra.style.display = 'block';
        oj.AnimationUtils['expand'](self.panel, {'startMaxHeight': self.initHeight}).then(function() {
          self.expanded = true;
          self.buttonIcons({end:'oj-panel-collapse-icon'});
          self.buttonLabel('collapse');
        });
      }
    };

    self.connected = function() {
      // 这里才是获取DOM元素的正确时机
      self.panel = document.getElementById('panel');
      self.extra = document.getElementById('extra-content');
      self.initHeight = $(self.panel).css('height');
    };

    self.disconnected = function() {
      // Implement if needed
    };

    self.transitionCompleted = function() {
    };

    self.hello2 = function() {
      alert('hhhh');
    };
  }
  return new CustomerViewModel();
} );

额外注意点

  • Oracle JET的ViewModel生命周期函数(connected、disconnected等)是处理DOM相关操作的最佳时机,避免在ViewModel构造函数中直接操作DOM,因为此时DOM还未完成渲染。
  • 如果后续遇到类似的DOM元素获取问题,都可以优先考虑放到connected函数中执行。

内容的提问来源于stack exchange,提问作者user9007028

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 10:08:14