簡體   English   中英

用.trigger()模擬多個按鍵;

[英]Simulating Multiple key-presses with .trigger();

目前,我正在編寫一個腳本,當該腳本被注入Google Chrome控制台時,它將收集一些信息並將其形成為字符串,並采用該字符串並將文本轉換為每個字符各自的字符代碼。

我的問題在於,嘗試讓jQuery在輸入字段上模擬按鍵,然后將字符代碼輸入該字段。

看一下我的代碼:

var text = $('[id^="nhwMiddlegwt-uid"]').html();
var text_middle = $('[id^="nhwMiddleCommagwt-uid"]').html();
var text_after = $('[id^="nhwRightgwt-uid"]').html();
var finished = text + text_middle + text_after;

console.log(finished);
var output, output_format = "";
for(i=0; i<finished.length; i++) {
    if(output != "") output += ", ";
    output += finished.charCodeAt(i);
}

輸出變量包含這樣的文本:“ 87、101、98、32、68、101、118、101、108、111、112、109、101、110、116”,是“ Web開發”的字符代碼”。

現在,我需要使用字符代碼字符串“輸出”並更改輸入字段的值。

我嘗試使用類似於以下內容的東西:

var e = jQuery.Event("keydown");
e.which = 84; // # Some key code value
$(".txtInput").val(String.fromCharCode(e.which));
$(".txtInput").trigger(e);

現在,如果您僅嘗試觸發一個按鍵(84)的按鍵模擬,則此方法有效,但不適用於我的整個輸出變量。 我已經嘗試過for循環,但是.trigger()事件不允許我這樣做,因為for循環中不允許添加到變量末尾的.which命令,請看下面:

for(i=0; i<finished.length; i++) {
        if(output != "") output += ", ";
        output.which += finished.charCodeAt(i);
}

所以,我怎么能得到.trigger(); 遍歷選項變量中的每個字符代碼?

編輯:只是為了澄清,我不想只是更改輸入值。 我想使用“輸出”變量字符代碼在輸入字段上模擬按鍵。

嘗試

var arr = [
    87
    , 101
    , 98
    , 32
    , 68
    , 101
    , 118
    , 101
    , 108
    , 111
    , 112
    , 109
    , 101
    , 110
    , 116
    ];

var output = String.fromCharCode.apply(String, arr);

$("#txtInput")
.on("keydown.str", function(e) {
  alert(e.target.value)
})
.prop("value", output)
.trigger("keydown.str");

 var arr = [ 87 , 101 , 98 , 32 , 68 , 101 , 118 , 101 , 108 , 111 , 112 , 109 , 101 , 110 , 116 ]; var output = String.fromCharCode.apply(String, arr); $("#txtInput") .on("keydown.str", function(e) { alert(e.target.value) }) .prop("value", output) .trigger("keydown.str"); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <input id="txtInput" type="text" /> 

暫無
暫無

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

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