如何在jquery或javascript中制作html列表?

时间:2017-09-07 09:46:39

标签: javascript jquery html list

我想在HTML中创建一个列表,然后用户选择列表,然后对选择做一些事情。

例如。水果清单。 Apple bannana,葡萄。

用户选择葡萄,如果选择葡萄,询问葡萄多少?

我想知道如何在Javascript或Jquery中执行此操作

1 个答案:

答案 0 :(得分:1)

使用此代码块。就这么简单,



//generates the list
var items = 'Apple, bannana, grapes';
var nHtml = '';
items = items.split(',');
items.forEach(function(v){
   //trim() will remove the blank spaces
   nHtml+='<li>'+ v.trim() +'</li>';
});
$('#itemList').append('<ul>'+ nHtml +'</ul>');

//detect click on the list item
$('li').click(function(){
   var name = $(this).text();
   var question = 'How many '+name+' ?';
   $('#question').html('<span>'+ question +'</span><input type="text" id="answer" />')
});

//get the number feed into the text box
function getCount(){
  var answer = $('#answer').val();
  console.log(answer);
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='itemList'></div>
<div id='question'></div>
<button onclick='getCount()'>Get Count</button>
&#13;
&#13;
&#13;