简体   繁体   English

function 的某些部分在按键事件监听器中不起作用

[英]Some part of a function doesn't work in keypress eventListener

I have a problem with not working part of a JavaScript code under some specific conditions.在某些特定条件下,我遇到了无法使用 JavaScript 代码的一部分的问题。 I have a task to do some simple credit card validation.我的任务是做一些简单的信用卡验证。 If a card number starts with a specific number I need to show a specific card icon like Visa or Mastercard.如果卡号以特定数字开头,我需要显示特定的卡图标,例如 Visa 或 Mastercard。 At the start 3 of them are shown and as I'm typing card number 2 of them should disappear and if the number has the correct length for that specific card type the remaining one should turn green.在开始时显示了其中的 3 个,当我输入卡号时,其中的 2 个应该消失,如果该数字具有该特定卡类型的正确长度,则其余的应该变为绿色。 The problem is when I try putting it in the eventListener for keypress nothing happens but when I try putting it outside the function everything works.问题是当我尝试将它放入 eventListener for keypress 时没有任何反应,但是当我尝试将它放在 function 之外时,一切正常。 For example:例如:

cardNumber.addEventListener("keypress", function(){
    if(cardNumber.value.startsWith("4")){
        cards[0].style.color = "green"
    }
})

This doesn't work, the card doesn't turn green when I'm typing number 4 but if I try to just console log something when I type number 4 then it's shown in the console, so the event listener works but for some strange reason the styling doesn't.这不起作用,当我输入数字 4 时卡片不会变成绿色,但是如果我在输入数字 4 时尝试控制台记录某些内容,那么它会显示在控制台中,因此事件侦听器可以工作,但对于一些奇怪的原因样式不。 But if I just try doing但如果我只是尝试做

cards[0].style.color = "green"

outside of the function just to see if I'm doing then the icon turns green normally.在 function 之外只是为了看看我是否在做然后图标正常变为绿色。

JavaScript: JavaScript:

const cardNumber = document.getElementById("cardNumber");
const cards = document.querySelectorAll("i");

cardNumber.addEventListener("keypress", function(){
    if(cardNumber.value.startsWith("4")){
        cards[0].style.color = "green"
        console.log("YES");
    }
})

HTML: HTML:

<main class="container">
  <div class="card mt-4">
    <div class="card-body">
      <form>
        <div class="form-group">
          <label for="cardNumber">Credit card number</label>
          <div class="input-group">
            <input type="text" class="form-control" id="cardNumber">
            <div class="input-group-append">
              <span class="input-group-text text-muted" style="font-size: 1.5rem" id="type">
                <i class="fab fa-cc-visa mx-1" id="visa-icon"></i>
                <i class="fab fa-cc-amex mx-1" id="amex-icon"></i>
                <i class="fab fa-cc-mastercard mx-1" id="mastercard-icon"></i>
              </span>
            </div>
          </div>
        </div>
      </form>
    </div>
  </div>
</main>

I can't change anything in the HTML - it's a JavaScript task.我无法更改 HTML 中的任何内容 - 这是 JavaScript 任务。

Edit: Moving the constant variables containing card icons inside the eventListener worked.编辑:在 eventListener 中移动包含卡片图标的常量变量有效。

You can try waiting till page is fully loaded, or inserting your code below the elements you wish to modify.您可以尝试等到页面完全加载,或者在您要修改的元素下方插入代码。 DOM state could be messing with you. DOM state 可能会惹恼你。

window.onload = (event) => {
  console.log('Code can go here');
};

Change the event you listen to input.更改您收听的事件输入。

cardNumber.addEventListener("input", function(){ cardNumber.addEventListener("输入", function(){

The problem with keypress is that the input is modified just after the event is triggered. keypress 的问题是输入在事件触发后被修改。

 const cardNumber = document.getElementById("cardNumber"); const cards = document.querySelectorAll("i"); cardNumber.addEventListener("input", function(e){ if(cardNumber.value.startsWith("4")){ cards[0].style.color = "green" } })
 <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.2/css/all.min.css" integrity="sha512-HK5fgLBL+xu6dm/Ii3z4xhlSUyZgTT9tuc/hSrtw6uzJOvgRr2a9jyxxT1ely+B+xFAmJKVSTbpM/CuL7qxO8w==" crossorigin="anonymous" /> <main class="container"> <div class="card mt-4"> <div class="card-body"> <form> <div class="form-group"> <label for="cardNumber">Credit card number</label> <div class="input-group"> <input type="text" class="form-control" id="cardNumber"> <div class="input-group-append"> <span class="input-group-text text-muted" style="font-size: 1.5rem" id="type"> <i class="fab fa-cc-visa mx-1" id="visa-icon"></i> <i class="fab fa-cc-amex mx-1" id="amex-icon"></i> <i class="fab fa-cc-mastercard mx-1" id="mastercard-icon"></i> </span> </div> </div> </div> </form> </div> </div> </main>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM