'value.length'为null或不是对象

时间:2011-08-15 15:19:16

标签: javascript

导致此错误的原因是什么?我应该将element.value传递给函数吗?我知道如何在JSP中设置它,但不是在JavaScript中。我在将值传递到另一个函数时遇到了麻烦。

function editCommentToggle( id )
{
    theRow = document.getElementById("id"+id);
    //user = theRow.cells[0].innerHTML;
    //date = theRow.cells[1].innerHTML;
    com = theRow.cells[2].innerHTML;


    idx = 2;
    maxlength = 250;
    // Comment field

    cell = theRow.cells[idx];
    while( cell.childNodes.length > 0 )
        cell.removeChild(cell.childNodes[0]);
    element = document.createElement("textarea");
    element.id="comments-"+id;
    element.rows="3";
    element.value = com;
    element.style.width = "400px";
    element.maxLength = "250";
    element.onfocus = element.onkeydown = element.onkeyup = function(){
            return characterCounterEdit(undefined, maxlength, element);
    }; 
    cell.appendChild(element);



function characterCounterEdit(id, maxLen, inputElement)
{
    spanId = document.getElementById(id);

    if (spanId)
    {
        // Update the counter the user sees.
        var whatIsLeft = maxLen - inputElement.value.length;

        if ( whatIsLeft < 0 ) whatIsLeft = 0;
        spanId.innerText = whatIsLeft;
    }

    // Restrict user from entering more than the maxlen.
 **ERROR HERE-->>>**   if ( inputElement.value.length > maxLen )
    {
        inputElement.value = inputElement.value.substring( 0, maxLen );
    }
}

2 个答案:

答案 0 :(得分:2)

尝试改变这个......

element.onfocus = element.onkeydown = element.onkeyup = function(){return characterCounterEdit(undefined, maxlength, element);};

到此......

element.onfocus = element.onkeydown = element.onkeyup = function(){return characterCounterEdit(undefined, maxlength, this);};
                                                                                                                     ^^^^

或者您也可以在characterCounterEdit函数中尝试使用此处描述的事件目标/ sourceElement - http://www.quirksmode.org/js/events_properties.html

答案 1 :(得分:1)

    element.onfocus = element.onkeydown = element.onkeyup = function(){return characterCounterEdit(undefined, maxlength, element);}; 

如果这是调用characterCounterEdit函数的唯一位置,那么在触发focus / keydown / keyup事件时,element很可能被赋予了一些OTHER值,该值没有.value属性。

而不是传入elementmaxlength(在事件被触发时可能不再存在),请执行以下操作:

element.maxlength = maxlength
element.onfocus = element.onkeydown = element.onkeyup = function(){return characterCounterEdit();}; 

function characterCounterEdit() {
    ....
    var whatIsLeft = maxLen - this.value.length;
                                     ^^^^--- use 'this' instead.
    ....
    if ( this.value.length > this.maxlength ) ...
    ....

}