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

XHTML页面body onload事件失效及TypeError报错求助

问题排查与解决方案

问题原因

  • 元素ID不匹配:JavaScript代码中尝试获取ID为Bezier_Curve_Button的按钮,但XHTML页面里按钮的实际ID是My_Button,导致document.getElementById返回null,后续调用setAttribute时触发Cannot set properties of null错误。
  • setAttribute语法错误:调用setAttribute时错误使用了赋值运算符=,正确的方法调用应该直接传递参数,不需要等号。

修复步骤

  1. 修正按钮ID匹配:将JavaScript中获取按钮的代码改为使用页面中实际存在的My_ButtonID。
  2. 修复setAttribute调用语法:移除多余的=符号,按照方法调用的正确格式传递参数。
  3. 可选优化:添加元素存在性检查,避免因元素缺失再次引发类似错误;使用元素的style属性直接设置样式,比setAttribute更直观。

修正后的JavaScript代码

function Setup() {
    var Bezier_Curve_Identification;
    var Attribute_Name;
    var Attribute_Name_2;
    var Coordinate;
    var My_Properties;
    var Button_Identification;

    Attribute_Name = "d";
    Attribute_Name_2 = "style";
    My_Properties = "stroke: blue; stroke-width: 3; fill: none;";
    Coordinate = "M 375 200 A 50 50 0 0 1 475 200";
    
    // 修正按钮ID,并检查元素是否存在
    Button_Identification = document.getElementById('My_Button');
    if (Button_Identification) {
        // 修正setAttribute语法
        Button_Identification.setAttribute("style", "top: 100px; height: 200px;");
        // 可选写法:直接操作style属性
        // Button_Identification.style.top = "100px";
        // Button_Identification.style.height = "200px";
    }
    
    Bezier_Curve_Identification = document.getElementById('Bezier_Curve_1');
    if (Bezier_Curve_Identification) {
        Bezier_Curve_Identification.setAttribute(Attribute_Name, Coordinate);
        Bezier_Curve_Identification.setAttribute(Attribute_Name_2, My_Properties);
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 11:55:02