代码之家  ›  专栏  ›  技术社区  ›  Shayki Abramczyk Cece Dong - MSFT

以编程方式输入值时,HTML输入元素无法识别值

  •  1
  • Shayki Abramczyk Cece Dong - MSFT  · 技术社区  · 7 年前

    $('#copy').click(function() {   
           var newClipboard = {
          "name": $('#buyercontactname').val(),
      }
    chrome.runtime.sendMessage({newClipboard: newClipboard});
    });
    

    要将数据粘贴到另一个站点,我使用以下代码:

    $(document).ready(function() {
        chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
            if (request.paste) {
                if (!(request.clipboard.name === '')) {
                    var nameParts = request.clipboard.name.split(' ');
                    $('[id="shippingFirstName"]').val(nameParts[0])
                    $('[id="shippingLastName"]').val(nameParts[1]);
                }
              }
            }
        });
    });
    

    id div input

    问题是:

    如果我将值粘贴到 部门 它工作得很好,但是如果我把值粘贴到 输入 无法识别,我需要按一个键。

    例如:

    enter image description here

    单击“保存”后(出现错误,字段为空):

    enter image description here

    在我按下字段上的一个键(甚至我按下“空格”)之后:

    enter image description here

    这个 输入 elemant看起来像这样:

    <input ng-model="user.first_name" id="shippingFirstName" name="shippingFirstName" prefix-attrs-with="shipping" value="" pattern="(?!^\d+$)^.+$" autocapitalize="off" autocomplete="off" maxlength="100" xo-error-tooltip="" ng-required="true" data-test-id="user.first_name" class="ng-pristine ng-empty ng-valid-pattern ng-invalid ng-invalid-required ng-valid-maxlength hasErrorTooltipRequired ng-touched focused" required="required" aria-describedby="nbafrxk" aria-invalid="true">
    

    我该怎么解决?

    2 回复  |  直到 5 年前
        1
  •  3
  •   Chinmoy Samanta    7 年前

    link .

    document.querySelector('[id="shippingFirstName"]').value=nameParts[0];
    document.querySelector('[id="shippingLastName"]').value=nameParts[0];
    document.querySelector('[id="shippingFirstName"]').dispatchEvent(new Event("input", { bubbles: true }));
    document.querySelector('[id="shippingLastName"]').dispatchEvent(new Event("input", { bubbles: true }));
    
        2
  •  0
  •   Carol Ng    7 年前

    看看这个问题: val() doesn't trigger change() in jQuery

    总之,看起来 .val() 它本身可能不会触发文本字段的更改事件,但您可以在更改值后通过运行以下命令手动触发它:

    $('[id="shippingFirstName"]').trigger("change");
    

    如果 change() 如果不触发它,您可以尝试更大的事件列表来触发put字段中的更改:

    $('[id="shippingFirstName"]').keydown();
    $('[id="shippingFirstName"]').keypress();
    $('[id="shippingFirstName"]').keyup();
    $('[id="shippingFirstName"]').focus();