2016-11-30 116 views
0
<input class="foo" type="text" /> 
<button>click</button> 

$('button').click(function(){ 
    var e = $.Event('keypress'); 
    e.which = 65; // Character 'A' 
    $('.foo').trigger(e); 
}); 

我尝试触发键盘事件并将文本添加到输入文本中。Javascript按钮单击触发按键并将文本添加到输入文本

出于某种原因,我不能使用= html or text(),我必须触发键盘事件

人知道如何解决这一问题?

+1

输入具有'value'(或jQueryland里的东西都不同,仅仅是为了为了不同,'val') - 不是'text'或'html' –

回答

2

TRY这样的:String.fromCharCode(e.which)。新增与$(element).val()。没有输入利用需要使用触发事件.simply负载数据元素。它够了。

$('button').click(function(){ 
 
    var e = $.Event('keypress'); 
 
    e.which = 65; // Character 'A' 
 
    $('.foo').val(String.fromCharCode(e.which)); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<input class="foo" type="text" /> 
 
<button>click</button>

另一个答案contentEditable

$('button').click(function(){ 
 
    var e = $.Event('keypress'); 
 
    e.which = 65; // Character 'A' 
 
    $('.foo').text(String.fromCharCode(e.which)); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div class="foo" contentEditable="true" ></div> 
 
<button>click</button>

+0

怎么样contenteditable div里面的文字? –

+0

这不会触发按键事件: –

+0

也不需要创建事件对象 –

相关问题