使用getElementById更改样式背景属性

问题描述 投票:0回答:2

如果我点击错误功能,如何更改文本框颜色?我尝试以下代码,但它不起作用只会显示错误消息。

<Script>
function fnName(ID)
{
    var flag = true;
    if(document.mainform.NAME.value == "")
    {
        error_function("Please enter the Name.",ID);
        flag = false;
    }
    else
    {
        release_function(ID)
        flag = true;
    }
    return flag;
}
function error_function(message,IDs)
{
        var ID = '"' + IDs + '"';

        document.getElementById("proposererrMsg").innerHTML     = message;
        document.getElementById("proposererrMsg").style.display = "inline";
        document.getElementById(ID).style.background  = "#DDDDDD";  //this line not working
         document.getElementById(ID).style.border    = "thin solid red"; // this line not working

}
</script>

 <label id="proposererrMsg" class="errMsg"></label> 
 <input type="text" name="NAME" id="NAME" value="<%=NAME%>" onblur="fnName(this.id);" />
javascript dom simple-html-dom
2个回答
2
投票

您使用的ID具有不必要的引号,因此您尝试引用具有不存在ID的元素,只需直接使用IDs参数:

document.getElementById(IDs).style.background = "#DDDDDD";


-1
投票

使用MDN - backgroundColor

<script>
function fnName(id){
    document.getElementById(id).style.backgroundColor = "red";
}
</script>
 <input type="text" name="NAME" id="NAME" value="" onblur="fnName(this.id);" /
© www.soinside.com 2019 - 2024. All rights reserved.