【问题标题】:Why is this JS/jQuery acting on multiple inputs?为什么这个 JS/jQuery 作用于多个输入?
【发布时间】:2019-03-12 03:32:50
【问题描述】:

代码在名称为“电话”的输入字段上按预期工作。它会在用户键入电话号码时对其进行格式化。但是,它正在向另一个名为“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>

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

【问题讨论】:

  • 使用 'id' 而不是 'input[name=phone]'。 $('#phone')
  • @TharakaDilshan 不起作用。出于某种原因,仍然适用于“双因素”。但是,它仍然适用于#phone 输入。

标签: javascript jquery laravel vue.js


【解决方案1】:

已解决

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

【讨论】:

    【解决方案2】:

    我刚刚复制了你的代码,就像你发送的一样,没有事件监听器附加到'twofactor'输入,你可以在这里看到。也许问题出在其他脚本或你没有提出问题,因为仅使用您发送的代码,一切都按预期工作。

    【讨论】:

    • 没有其他脚本影响输入。当我将 vue 指令切换到 v-show 时,它得到了修复。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多