2012-05-21 66 views
1

關於.trigger() method的jQuery的按鍵事件,該Event objectwhich propertyJS char codes和下面的代碼,爲什麼#example輸入沒有得到a自動寫入值的字符?我誤解了.trigger()方法嗎?上觸發輸入文本

<input type="text" name="example" id="example" value="" /> 

<script> 
$(function() { 
    var e = jQuery.Event("keydown", { which: 65 }); 
    $("#example").focus().trigger(e); 
}); 
</script> 

回答

5

你正在做的錯誤是你期待的jQuery的trigger方法做什麼。如果檢查出code你會看到它是什麼做的是實際執行的jQuery註冊的事件處理的DOM Level 3的事件。因爲它只執行jQuery處理程序,所以不會導致change事件,這是您需要觸發以更新文本框的value屬性的事件。

0

作爲每documentation

附有.bind任何事件處理程序()或它的快捷方式的方法之一,當相應的事件發生時被觸發。

$('#foo').bind('click', function() { 
    alert($(this).text()); 
}); 
$('#foo').trigger('click'); 

在你的情況,這將是:

$('#example').bind('keydown', function(e) { 
    alert("Pressed: " + e.keycode()); 
}); 
$('#example').focus().trigger('click'); 
0

可能過於簡化的東西,但不能你只是改變輸入字段的.val()(值)來模擬auto-written values

你可以簡單地這樣設置值 - 之間

var autoText = ['f','o','o','b','a','r']; 
var characterIndex = 0; 
var autoType = setInterval(function(){ 
    $("#example").val($("#example").val() + autoText[characterIndex]); 
    characterIndex++; 
    if (characterIndex >= autoText.length){ 
    clearInterval(autoType); 
    } 
},_keystroke_interval); 

_keystroke_interval是間隔(毫秒) -

$("#example").val('Some auto-written value'); 

諸位可以做一些更直觀這樣自動鍵入的字符。 autoType區間變量將遍歷autoText數組的所有索引,並且對於每次迭代,它都會將一個字符附加到輸入字段。

這會給你更多的自動打字感覺......

here is a working jsFiddle example