2014-10-29 44 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);