我试图创建一些javascript来插入文本限制,而不必单独引用每个textarea,但是如果出现必须省略textarea的情况,请使用类。我的调试器没有表现,visual studio无法跟踪智能,而jsfiddle也没有报告错误。我对如何调试这个问题感到有些困惑。如果它使用jquery,我真的不在乎。我有一个工作版本的代码,它只使用css id而不是类。
$('.txtFeedback').html("characters remaining");
try {
$(document).ready(function() {
var textareas = document.getElementsByClassName("txtLimit");
var feedbacks = document.getElementsByClassName("txtFeedback");
var n = 0;
for (var i = 0; i < textareas.length; i++) {
var thisElem = textareas[i];
var countX = textareas[i].style.marginLeft;
$("#" + thisElem.id).keyup(function() {
var text_length = $("#" + thisElem.id).val().length; //char count
var text_remaining = $("#" + thisElem.id).maxLength - text_length;
if (countX < thisElem.maxLength) {
$("#" + feedbacks[n].id).css({
marginLeft: '+=50pt'
});
countX += 50;
}
$("#" + feedbacks[n].id).html(text_length + '/' + text_max);
});
n++;
}
});
} catch (err) {
document.getElementById("errors").innerHTML = err.message;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="textarea" class="txtLimit" rows="8" cols="30" maxlength="99" style="z-index:1;"></textarea>
<div id="textarea_feedback" class="txtFeedback" style="z-index:2; margin-top:-18pt; margin-left:50pt"></div>
<div id="errors" width=100 height=3 00/>
&#13;
答案 0 :(得分:1)
问题是您需要先将反馈元素存储到变量中,然后才能尝试获取其ID。我更新了你的代码片段。另外,我发现text_max
变量没有定义,所以我随意定义为300.
仅供参考,您可以使用JSFiddle中的开发者控制台(按F12)查看错误。
编辑:根据评论,我已将text_max
更新为thisElem.maxLength
。
$('.txtFeedback').html("characters remaining");
try {
$(document).ready(function() {
var textareas = document.getElementsByClassName("txtLimit");
var feedbacks = document.getElementsByClassName("txtFeedback");
for (var i = 0; i < textareas.length; i++) {
var thisElem = textareas[i];
var text_max = thisElem.maxLength;
var feedback = feedbacks[i];
var countX = textareas[i].style.marginLeft;
$("#" + thisElem.id).keyup(function() {
var text_length = $("#" + thisElem.id).val().length; //char count
var text_remaining = $("#" + thisElem.id).maxLength - text_length;
if (countX < thisElem.maxLength) {
$("#" + feedback.id).css({
marginLeft: '+=50pt'
});
countX += 50;
}
$("#" + feedback.id).html(text_length + '/' + text_max);
});
}
});
} catch (err) {
document.getElementById("errors").innerHTML = err.message;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="textarea" class="txtLimit" rows="8" cols="30" maxlength="99" style="z-index:1;"></textarea>
<div id="textarea_feedback" class="txtFeedback" style="z-index:2; margin-top:-18pt; margin-left:50pt"></div>
<div id="errors" width=100 height=3 00/>
&#13;