javascript - 为什么这个 JS/jQuery 作用于多个输入?
问题描述
该代码在名称为“电话”的输入字段上按预期工作。它会在用户键入电话号码时对其进行格式化。但是,它正在向另一个名为“twofactor”的输入添加一个事件侦听器,我无法弄清楚为什么事件会触发并格式化输入。
JS
$('input[name=phone]').keypress(function (e) {
if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
return false;
}
var curchr = this.value.length;
var curval = $(this).val();
if (e.which == 49 && curchr == 0) {
return false;
}
if (curchr == 3 ) {
$(this).val(curval + "-");
} else if (curchr == 7) {
$(this).val(curval + "-");
} else if (curchr == 12) {
$(this).attr('maxlength', '12');
}
});
刀片中的 HTML
<form v-if="!errors.has('hours') && !has_phone_2fa" class="phone-form" action="#" @submit.prevent="send2FA" @keydown="errors.clear($event.target.name)" onkeypress="return event.keyCode !== 13;">
<p v-show="!ordering && items && items.length !== 0">We take orders exclusively via text. It's quick, easy and allows you to reach us anytime with Q's.</p>
<input type="tel" id="phone" name="phone" v-show="!ordering && items && items.length !== 0" v-model="model.phone" class="input" placeholder="Cell Number">
<span class="error-text" v-if="errors.has('phone')" v-text="errors.get('phone')"></span>
<button v-show="!ordering && items && items.length !== 0" @click="send2FA" type="button">Checkout</button>
</form>
<form v-if="!errors.has('hours') && has_phone_2fa" action="#" @submit.prevent="onPhoneValidate" @keydown="errors.clear($event.target.name)" onkeypress="return event.keyCode !== 13;">
<p>Please enter the 6-digit code we just sent you to validate your phone number.</p>
<input type="tel" id="twofactor" v-model="user_phone_2fa" name="twofactor" placeholder="6-digit Code">
<span class="error-text" v-if="errors.has('2fa')" v-text="errors.get('2fa')"></span>
<button @click="onPhoneValidate" type="button">Verify</button>
</form>
解决方案
解决了
我想通了,但不确定为什么会这样。它与 vue 指令有关。“v-if”会导致错误,但“v-show”不会并允许它完美地工作。如果有人可以回答为什么会发生这种情况,我会接受答案。
推荐阅读
- python - 在数据框中添加新行并有条件拆分前一行
- javascript - 我的 RESTful API 没有更新数据库,但 ajax 返回成功
- cordova - 无法找到或加载主类 org.gradle.wrapper.GradleWrapperMain android 构建错误
- java - 无法解析导入组织 (json)
- javascript - 在一种方法中进行 ajax 调用时,不会按顺序触发单击和更改事件
- php - 如何mysql剪切文本字段的结尾部分然后移动到其他文本字段的开头
- java - STS 插件未显示
- jquery - 在 laravel 中使用 ajax 和 jquery 上传多张图片
- python - 转换 pandas 数据框以用于 MultiLabelBinarizer
- android - 如何使用可为空的参数模拟私有方法