如果我在表 1 上使用 ctrl c 和 ctrl v 粘贴文本(例如在“Apple”上),表 2 上输入的重复文本仍然会更改,但是如果我使用右键单击并粘贴进行粘贴,表 2 上的重复输入不会改变。 :( 我创建了两个不同的事件(keyup 和 change)但是当使用右键单击粘贴文本时似乎没有任何效果。请看下面:
$(document).off('keydown').on('keydown', $('#table1 tbody tr td input:eq(0)'), function (e) {
var oldValue =$(e.target).val();//get the input value before keypress or edit
$(document).on('keyup', $('#table1 tbody tr td input'),function(e){
$('#table2').find('td input').each(function(){
if($(this).val() === oldValue){
$(this).val($(e.target).val());
}
$(document).off('keyup');
});
});
});
var oldValue;
$(document).on('keydown', '.main', function (e) {
oldValue = $(this).val();
foo(oldValue);
});
var newValue;
$(document).on('keyup', '.main', function (e) {
newValue = $(this).val();
foo(oldValue);
});
function foo(oldValue) {
$('#table1').find('tbody tr').find('td input').change(function (i) {
var orig = $(this).val();
$('#table2 tbody tr').find('td input').each(function (i) {
if (oldValue == $(this).val()) {
$(this).val(orig);
}
});
});
}
最佳答案
您可以计算更改时的字符数(因为您一次只能输入一个字符。
编辑:
为什么它不起作用:
在你的 jsfiddle 上记得在框架和扩展中设置 onDomReady
相当于 $(document).ready(handlerFn)
当您在输入上使用 on('change', handlerFn)
或 .change(handlerFn)
时,它只会在文本框失去焦点后触发( 模糊
)。响应不像您在表单上使用 select
时那样是即时的。使用 bind("input", handlerFn)
而不是 on(change)
进行输入。
下面的代码将从#table1 上编辑的单词更新到#table2 上的匹配词。更新将适用于复制粘贴 CTRL C/V 或鼠标复制/粘贴事件。它还会通过比较新旧值的长度来提醒用户是否复制/粘贴。
$("#table1 >* input").each(function() {
var elem = $(this),
oldValue;
elem.on('focus', function () {
elem.data('oldVal', elem.val());
elem.data('oldLen', elem.data('oldVal').length);
});
// Look for changes in the value,
// bind 'input' event to the textbox to fire the function
// every time the input changes (paste, delete, type etc.)
elem.bind("input", function(event){
oldValue = elem.data('oldVal');
// update oldVal
elem.data('oldVal', elem.val());
// check if pasted
if (elem.val().length - elem.data('oldLen') > 1 ) {
alert('Most certainly pasted');
}
// update input value length
elem.data('oldLen', elem.data('oldVal').length);
// update #table2
foo(oldValue, elem.val()) ;
});
});
更新#table2的函数
function foo(oldValue, newValue) {
$('#table2')
.find('input')
.each(function (i) {
if (oldValue === $(this).val()) {
$(this).val(newValue);
}
});
}
这是一个 jsfiddle给你玩
关于javascript - 如何检测是否使用右键单击粘贴了文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28183621/