簡體   English   中英

Javascript - 更新輸入值后按回車鍵

[英]Javascript - press enter key after updating input value

我正在嘗試使用 Javascript 以編程方式按下回車鍵,但只有在更新輸入值之后,也使用 Javascript。

它正在成功更新值,但沒有按回車鍵。

請注意,有多個inputs ,以下代碼在所有inputs的循環內。

// update value of input
document.querySelectorAll("input[type='number']")[index].value = 5;
// press enter key
var el = document.querySelectorAll("input[type='number']")[index];
var ev = new KeyboardEvent('keydown', {altKey:false,
    bubbles: true,
    cancelBubble: false, 
    cancelable: true,
    charCode: 0,
    code: "Enter",
    composed: true,
    ctrlKey: false,
    currentTarget: null,
    defaultPrevented: true,
    detail: 0,
    eventPhase: 0,
    isComposing: false,
    isTrusted: true,
    key: "Enter",
    keyCode: 13,
    location: 0,
    metaKey: false,
    repeat: false,
    returnValue: false,
    shiftKey: false,
    type: "keydown",
    which: 13});
el.addEventListener('keydown', function () { 
    console.log("Press enter now");
    el.dispatchEvent(ev);
});

PS - 這是一個 chrome 擴展,用於操作網頁的輸入,這些輸入需要按下回車鍵,以更新購物車。

我認為您正確地看到了這個問題; 您正在嘗試在keydown偵聽器中調度keydown事件,該偵聽器將以無限循環結束。

如果要在以編程方式更新值后調度keydown事件,則應將調度行放在值更改行之后:

document.querySelectorAll("input[type='number']")[index].value = 5;
el.dispatchEvent(new Event('keydown'));

如果你不是觸發價值變化的人,那就有點不同(而且更復雜)。 這是解決該確切問題的問題 1問題 2

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM