2014-10-29 48 views
1

在这个测验中,我正在做的是首先点击您想输入文本的文本框,然后点击您想要放在框中的按钮。 问题 - 如果我想将值abcdefghi放在框中。 如果我点击第一个按钮,然后第二个按钮,先前的内容被删除。填写空格测验

<html> 
<head> 
</head> 

<body><button class="b"></button> 
<button class="a">abc</button> 
<button class="a">def</button> 
<button class="a">ghi</button> 

<div class="fill" id="f1"><input type="text" style="border:" value="">aaa</div> 
<div class="fill" id="f2"><input type="text" value="">bbbb</div> 
<div class="fill" id="f3"><input type="text" value="">ccc</div> 


    <script src="jquery.min.js"></script> 
<script type="text/javascript"> 

var activeFill; 

    $('.fill input').on('click',function() { 
activeFill = $(this); 
}); 

    $('button').on('click',function() { 
    if (activeFill !== 'undefined') { 
    var val = $(this).html(); 
    $(activeFill).val(val); 
    } 
    }); 
    </script> 
    </body> 
    </html> 
+0

这里有一个JSF iddle http://jsfiddle.net/jza48Lt1/ – 2014-10-29 06:01:53

回答

0

每次更换的内容,你必须要追加的内容如下图所示

$('button').on('click',function() { 
    if (activeFill !== 'undefined') { 
    var val = $(this).html(); 
    //$(activeFill).val(val); -- remove this 
    // append content 
    var prevContent = $(activeFill).val(); 
    $(activeFill).val(prevContent + val); 
    } 
    }); 

但上面的代码会增加重复的值,如果你点击相同的按钮两次,以防止下面的代码的重复使用

$('button').on('click',function() { 
     if (activeFill !== 'undefined') { 
     var val = $(this).html(); 
     //$(activeFill).val(val); -- remove this 
     // append content 
     var prevContent = $(activeFill).val(); 
     if(prevContent.indexOf(val)==-1) // if condition to check if text already present or not 
      $(activeFill).val(prevContent + val); 
     } 
     }); 

编辑 - 由于OP CLEAR想和DELETE键的功能,请参见下面的代码

HTML -

<button class="delete">DELETE</button> 
<button class="clear">CLEAR</button> 

jQuery的

//variable to store last added text 
var lastAddedText = ''; 

$('button.a').on('click',function() { 
      if (activeFill !== 'undefined') { 
      var lastAddedText = $(this).html(); 
      // append content 
      var prevContent = $(activeFill).val(); 
      if(prevContent.indexOf(lastAddedText)==-1) // if condition to check if text already present or not 
       $(activeFill).val(prevContent + lastAddedText); 
      } 
      }); 

$('button.delete').on('click',function() { 
    var val = $(activeFill).val(); 
    val = val.substring(0,val.length-1); 
    $(activeFill).val(val); 
}); 

$('button.clear').on('click',function() { 
    $(activeFill).val(''); 
}); 

JSfiddle Demo

+0

谢谢你的帮助,但是如果我想要一个删除按钮以及假设该按钮与类b是删除按钮。 – 2014-10-29 06:05:48

+0

删除所有文本或只是上次输入的文本? – 2014-10-29 06:06:46

+0

最后一个索引应该被删除。 – 2014-10-29 06:08:14

0

很简单 - 你需要添加前值:

$(activeFill).val($(activeFill).val() + val);