首页 > 解决方案 > 为什么这个 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>

如您所见,在控制台中,它显示事件侦听器已附加到“双因素”输入...但是为什么会发生这种情况? 控制台窗口

标签: javascriptjquerylaravelvue.js

解决方案


解决了

我想通了,但不确定为什么会这样。它与 vue 指令有关。“v-if”会导致错误,但“v-show”不会并允许它完美地工作。如果有人可以回答为什么会发生这种情况,我会接受答案。


推荐阅读