Javascript:设置标签文本

MrG*_*MrG 17 javascript

我正在尝试为具有以下格式的多个字段的表单实现泛型函数.

<label id="LblTextCount"></label>
<textarea name="text" onKeyPress="checkLength(this, 512, LblTextCount)">
</textarea>
Run Code Online (Sandbox Code Playgroud)

以下JavaScript:

function checkLength(object, maxlength, label) {
    charsleft = (maxlength - object.value.length);

    // never allow to exceed the specified limit
    if( charsleft < 0 ) {
        object.value = object.value.substring(0, maxlength-1);
    }

    // I'm trying to set the value of charsleft into the label
label.innerText = charsleft;
    document.getElementById('LblTextCount').InnerHTML = charsleft;
}
Run Code Online (Sandbox Code Playgroud)

第一部分工作正常,但我无法将charsleft值设置到标签中.我究竟做错了什么?请注意,我正在寻找一种动态方法,而不是将标签名称硬编码到JS函数中.JQuery也会很好:)


解决方案 - 感谢所有人!

HTML

<label id="LblTextCount"></label>
<textarea name="text">
</textarea>
Run Code Online (Sandbox Code Playgroud)

JS

$(document).ready(function() {
    $('textarea[name=text]').keypress(function(e) {
        checkLength($(this),512,$('#LblTextCount'));
    }).focus(function() {
        checkLength($(this),512,$('#LblTextCount'));
    });
});

function checkLength(obj, maxlength, label) {
    var charsleft = (maxlength - obj.val().length);

    // never allow to exceed the specified limit
    if( charsleft < 0 ) {
        obj.val(obj.val().substring(0, maxlength-1));
    }

    // set the value of charsleft into the label
    $(label).html(charsleft);
}
Run Code Online (Sandbox Code Playgroud)

kar*_*m79 22

InnerHTML应该是innerHTML:

document.getElementById('LblAboutMeCount').innerHTML = charsleft;
Run Code Online (Sandbox Code Playgroud)

你应该checkLength使用jQuery 将你的函数绑定到你的textarea而不是内联调用它,而不是打扰它:

$(document).ready(function() {
    $('textarea[name=text]').keypress(function(e) {
        checkLength($(this),512,$('#LblTextCount'));
    }).focus(function() {
        checkLength($(this),512,$('#LblTextCount'));
    });
});
Run Code Online (Sandbox Code Playgroud)

你可以通过使用更多的jQuery来结束checkLength,我不会使用'object'作为形式参数:

function checkLength(obj, maxlength, label) {
    charsleft = (maxlength - obj.val().length);
    // never allow to exceed the specified limit
    if( charsleft < 0 ) {
        obj.val(obj.val().substring(0, maxlength-1));
    }
    // I'm trying to set the value of charsleft into the label
    label.text(charsleft);
    $('#LblAboutMeCount').html(charsleft);
}
Run Code Online (Sandbox Code Playgroud)

因此,如果您应用上述内容,则可以将标记更改为:

<textarea name="text"></textarea>
Run Code Online (Sandbox Code Playgroud)