避免更新keyup上的所有textareas

时间:2014-01-03 23:42:56

标签: javascript jquery html

我有这样的表格:

http://jsfiddle.net/uS898/

<input type="text" name="firstTarget" />
<input type="text" name="secondTarget" />
<input type="text" name="thirdTarget" />
<textarea name="result">I have this text and I want to update it using firstTarget. After that I want to use secondTarget and thirdTarget</textarea>
<textarea name="result">I only want to use secondTarget here</textarea>
<textarea name="result">I only want to use thirdTarget here</textarea>

和这个jquery

$('input').keyup(function(){
    var regVal=$(this).data('replace');    
   var newText=$('textarea').val().replace( regVal, this.value);   
    $(this).data('replace', this.value)     
    $('textarea').val(newText);    
}).each(function(){
    $(this).data('replace', this.name); 
})

当我填写firstTarget输入时,它将单词“fistTarget”替换为firstTarget输入中写入的单词。 不知何故,当输入中写入某些东西时,我的代码会重置所有第二个和第三个textareas。 我不想重置textarea 2或textarea 3中的内容。 我该怎么办?

3 个答案:

答案 0 :(得分:0)

请在此处查看我的示例: DEMO

var delay = 1000;
var wait = (function(){
 var timer = 0;
 return function(callback, ms){
 clearTimeout (timer);
 timer = setTimeout(callback, ms);
};
})();

$('input').keyup(function(){
 var regVal=$(this).data('replace'); 
 var that = $(this);
 wait(function(){
   $('textarea').each(function(){
   var newText = $(this).val().replace( regVal, that.val());
   $(this).val(newText); 
  });
  }, delay);
 }).each(function(){
    $(this).data('replace', this.name);
 });

答案 1 :(得分:0)

要么我误解了你的目标,要么你可能会使事情过于复杂。如果您只是想将每个输入绑定到textarea,这就是您所需要的:

$('input').keyup(function(){
    var target_id = $(this).data('target');
    $('#' + target_id).val(this.value);
});

当然你必须更新一些属性,如下所示:

 <input type="text" data-target="firstTarget" />
    <input type="text" data-target="secondTarget" />
    <input type="text" data-target="thirdTarget" />
    <textarea style="width:500px; height: 100px;" id="firstTarget">I have this text and I want to update it using firstTarget. After that I want to use secondTarget and thirdTarget</textarea>
<textarea style="width:500px; height: 100px;" id="secondTarget">I only want to use secondTarget here</textarea>
<textarea style="width:500px; height: 100px;" id="thirdTarget">I only want to use thirdTarget here</textarea>

这是demo

答案 2 :(得分:0)

这个怎么样:http://jsfiddle.net/DP4a8/1/

$('input').keyup(function(){
    var input = this;
    var regVal=$(this).data('replace');    
    $('textarea').each(function() {
      var newText = this.value.replace(regVal, input.value);
      $(this).val(newText);
    });
    $(this).data('replace', this.value)     
}).each(function(){
    $(this).data('replace', this.name); 
})