2017-09-10 19 views
1

HTML:多.appends與點擊

<h1>Favorite Animal:</h1> 
<input type='text'> 
<button>Answer!</button> 
<div id='ans'></div> 

的Javascript(jQuery的)

$(document).ready(function(){ 
    $('button').click(function(){ 
     $('#ans').append('<h2>Bunny</h2>') 
    }) 
}) 

嘿。我在想。我可以做到這一點,當我在輸入中鍵入一個數字[type ='text'],然後讓這個數字的「兔子」出現? (例如:我輸入3,單詞「bunny」出現3次)。

回答

1

你可以用一個簡單的循環做到這一點:

$(document).ready(function() { 
 
    $('button').click(function() { 
 
    for (i = 0; i < $('input[type=text]').val(); i++) { 
 
     $('#ans').append('<h2>Bunny</h2>') 
 
    } 
 
    }) 
 
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<input type='text' /> 
 
<button>Answer!</button> 
 
<div id='ans'></div>

0

沒問題,只要創建許多索引的數組,並填寫

$(document).ready(function() { 
 
    $('button').click(function() { 
 
    var n = +$('input').val(); 
 
    var arr = $.map(Array(n), function() { 
 
     return $('<h2 />', {text : 'Bunny'}); 
 
    }); 
 

 
    $('#ans').empty().append(arr); 
 
    }) 
 
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<h1> 
 
    Favorite Animal: 
 
</h1> 
 
<input type='text'> 
 
<button> 
 
Answer! 
 
</button> 
 
<div id='ans'> 
 

 
</div>

+0

也許它值得一提的是所有瀏覽器都不支持'fill'方法(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/fill#Browser_compatibility)。 – SLePort

+0

@SLePort - 正確,'Array.fill'在IE中不受支持,但MDN有一個polyfill – adeneo

+1

幸運的是,jQuery解決了這個問題 – adeneo

0

是的,你可以得到用戶輸入的輸入,將它從一個字符串轉換爲一個數字,檢查它是否是一個介於1和1000之間的整數,然後在for循環中使用它。每次在for循環中添加元素。下面是一些例子How can val() return Number?您可以使用滑塊來做到這一點的使用HTML屬性,以確保數量是你希望它是

0

更有效,你可以這樣做:

$(document).ready(function(){ 
    $('button').click(function(){ 
     $('#ans').append('<h2>Bunny</h2>'.repeat($('input').val())) 
    }) 
}) 
0
You may try for This: 

1. In JS part: 


    $(document).ready(function() { 
      $('button').click(function() { 
      for (i = 0; i < $('input[type=text]').val(); i++) { 
       $('#ans').append('<h2>Bunny</h2>') 
      } 
      }) 
     }) 

2. in HTML part: 

    <input type='text' /> 
    <button>Answer!</button> 
    <div id='ans'></div>