我正在尝试做某种屏幕键盘。当我点击一个正方形时,它会在textarea上写一个特定的字母。
我想每次按一个新的方块(并写一个新的字母)时调用一个javascript函数。
使用真正的电脑键盘,我会使用“keyup”。但这里它不起作用(也不是“鼠标”)。
小型演示: http://jsfiddle.net/bcorreia/oq0sgk8g/
谢谢
HTML
<svg width="60px" height="60px">
<rect width="50" height="50" onclick="getElementById('text').value+='a'">
</svg>
<svg width="60px" height="60px">
<rect width="50" height="50" onclick="getElementById('text').value+='b'">
</svg>
<textarea id="text"></textarea>
JS
$(function(){
$("#text").keyup(function() {
console.log("test");
});
});
答案 0 :(得分:1)
我会改变你实现这一点的方式。不是为每个矩形使用不同的内联单击事件处理程序,而是以编程方式将单击事件委派给所有矩形。要区分应附加的字符,可以将数据属性添加到包含它们所代表的字符的矩形中,并在单击处理程序中检索它们的值。要处理物理键盘输入,您可以专门为其设置单独的事件绑定。这是我如何处理这个问题的一个有效例子,并附有一些评论,以澄清它在做什么。
function yourOtherFunction(input) {
console.log('You typed a "' + input + '"');
}
$(function() {
// Handle on-screen keyboard clicks (only on rects with a data-character
// attribute present)
$('svg rect[data-character]').click(function() {
// Retrieve the "data-character" attribute value
var character = $(this).data('character');
// Modify the value of the textarea by appending the character
$('#text').val(function(i, old) { return old + character; });
// Call your other function
yourOtherFunction(character);
});
// Handle physical keyboard key presses:
$('#text').keypress(function(e) {
// Retrieve the character representation of the event's key code
var character = String.fromCharCode(e.which);
// Call your other function
yourOtherFunction(character);
});
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<svg width="60px" height="60px">
<rect width="50" height="50" data-character="a" />
</svg>
<svg width="60px" height="60px">
<rect width="50" height="50" data-character="b" />
</svg>
<textarea id="text"></textarea>
&#13;