我有某种形式,可以防止在填充第一个输入之前填充第二个输入文本,这是我的代码
function autotab(current,to){
if (current.getAttribute &&
current.value.length==current.getAttribute("maxlength")) {
//to.removeAttr('readonly');
to.focus();
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<div class="answers">
<input type="text" id="i1" name="i1" size=1 onKeyup="autotab(this, i2)" maxlength=1 autofocus><br>
<input type="text" id="i2" name="i2" size=1 onKeyup="autotab(this, i3)" maxlength=1 readonly><br>
<input type="text" id="i3" name="i3" size=1 onKeyup="autotab(this, i4)" maxlength=1 readonly><br>
我真正想要的是删除readonly
属性,我正在使用to.removeAttr('readonly')
,但是它显示错误Uncaught TypeError: to.removeAttr is not a function
,我已经尝试使用to.prop('readonly', false);
,但是没有。不能改变任何建议吗?
答案 0 :(得分:1)
原始的Javascript方法称为removeAttribute
:
to.removeAttribute('readonly');
如果要使用removeAttr
,则必须先将元素转换为jQuery集合:
function autotab(current, to) {
if (current.getAttribute &&
current.value.length == current.getAttribute("maxlength")) {
$(to).removeAttr('readonly');
to.focus();
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="answers">
<input type="text" id="i1" name="i1" size=1 onKeyup="autotab(this, i2)" maxlength=1 autofocus><br>
<input type="text" id="i2" name="i2" size=1 onKeyup="autotab(this, i3)" maxlength=1 readonly><br>
<input type="text" id="i3" name="i3" size=1 onKeyup="autotab(this, i4)" maxlength=1 readonly><br>
您还依赖于i2
等等,以引用内联处理程序中的元素。最好不要依赖它(有关详细信息,请参见this question)-更好地显式选择元素,并使用Javascript正确分配处理程序(通常认为内联处理程序是很差的做法)。这是一种重构方法:
const answers = document.querySelector('.answers');
answers.addEventListener('keyup', ({ target }) => {
if (target.value.length != target.getAttribute('maxlength')) return;
const next = target.nextElementSibling;
if (!next) return;
next.removeAttribute('readonly');
next.focus();
});
input {
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="answers">
<input type="text" id="i1" name="i1" size=1 maxlength=1 autofocus>
<input type="text" id="i2" name="i2" size=1 maxlength=1 readonly>
<input type="text" id="i3" name="i3" size=1 maxlength=1 readonly>
答案 1 :(得分:1)
to
是DOM对象。将其包装到$()
中可以解决您的问题:
function autotab(current,to){
if (current.getAttribute &&
current.value.length==current.getAttribute("maxlength")) {
$(to).removeAttr('readonly');
to.focus();
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<div class="answers">
<input type="text" id="i1" name="i1" size=1 onKeyup="autotab(this, i2)" maxlength=1 autofocus><br>
<input type="text" id="i2" name="i2" size=1 onKeyup="autotab(this, i3)" maxlength=1 readonly><br>
<input type="text" id="i3" name="i3" size=1 onKeyup="autotab(this, i4)" maxlength=1 readonly><br>