首页 > 解决方案 > 如果包含“-”,则更改 ASP.Net 标签文本颜色

问题描述

如果我的 ASP.net 标签包含“-”符号,我正在尝试更改它的文本/字体颜色。

这是一个百分比变化标签,因此负数需要为绿色,正数为红色。

我不断收到TypeError: document.getElementById(....) is null

我知道 window.onLoad 不是最佳实践,这只是为了快速测试它。

谁能告诉我我做错了什么……转圈圈。

window.onload = fillDays;

function fillDays() {
    var change = document.getElementById("<%=lblPercentageDifferenceToFillReqCurrentVsPreviousMonth %>").value;

    if (change.indexOf(char) = '-') {
        document.getElementById("<%=lblPercentageDifferenceToFillReqCurrentVsPreviousMonth %>").style.color = "green";
    }
    else {
        document.getElementById("<%=lblPercentageDifferenceToFillReqCurrentVsPreviousMonth %>").style.color = "red";
    }
    console.log("fillDays")
};

标签: javascriptasp.net

解决方案


你必须使用ClientID

var change = document.getElementById("<%= lblPercentageDifferenceToFillReqCurrentVsPreviousMonth.ClientID %>").value;

假设它是一个实际的 Control 像

<asp:TextBox ID="lblPercentageDifferenceToFillReqCurrentVsPreviousMonth" runat="server"></asp:TextBox>

推荐阅读