gpt4 book ai didi

带参数的Javascript字符计数器函数

转载 作者:行者123 更新时间:2023-11-29 21:20:11 25 4
gpt4 key购买 nike

我是 javascript 的初学者,我在某处找到了我的 EditorFor 字符计数器,现在它在代码中的样子如下:

<span class="text-length-counter" id="email_counter"></span>                  
@Html.EditorFor(model => model.ProfileFormDto.Email, new { htmlAttributes = new { @class = "form-control create-view-field", id="email_area" }})

这里是一个执行此工作的 javascript 函数:

 $(document).ready(function() {
var text_max = 50;
var text_length = $('#email_area').val().length;

$('#email_counter').html(text_length +' / ' + text_max + ' znaków');

$('#email_area').keyup(function() {
var text_length = $('#email_area').val().length;

$('#email_counter').html(text_length + ' / ' + text_max + ' znaków');
});
});

它工作正常,但我必须修改这个函数(),因为我必须在一页上使用许多计数器,所以上面的函数必须采用三个参数,例如:Count(counter,area,max)。我无法管理这个。在部分中有我的新函数声明:

        $(document).ready(function () {
Count('email_counter','email_area',50);
});

function Count(counter,area,max) {

var text_length = $('#area').val().length;

$('#counter').html(text_length +' / ' + max + ' znaków');

$('#area').keyup(function() {
var text_length = $('#area').val().length;

$('#counter').html(text_length + ' / ' + max + ' znaków');
});
};

它不工作,我得到错误:管理:169 未捕获类型错误:无法读取未定义的属性“长度”

最佳答案

您的 jQuery 选择器当前正在尝试选择 id="area"和 id="counter"的元素

如果要将area和counter转为参数,需要用$('#' + area)和$('#' + counter)进行选择。

有了这个更新,你的代码看起来像

function Count(counter, area, max) {
var text_length = $('#'+area).val().length;

$('#'+counter).html(text_length +' / ' + max + ' znaków');

$('#'+area).keyup(function() {
var text_length = $('#'+area).val().length;
$('#'+counter).html(text_length + ' / ' + max + ' znaków');
});
};

Here's a working jsfiddle具有多个输入字段。

关于带参数的Javascript字符计数器函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38729279/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com