用jQuery动态填充下拉列表 [英] Dynamically populating a dropdown with jQuery

查看:62
本文介绍了用jQuery动态填充下拉列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用jQuery从下拉列表中删除所有值?

How do I remove all the values from a dropdown list using jQuery?

idnum = "item-7";

,其中会填充一个包含7个项目的下拉菜单.我可以有一个"item-3",其中将包含三个项目.我想做的是选择一个按钮,其ID值可能为"item-X",其中X是要填充的条目数,因此根据我单击的按钮,它可能会有所不同.我想清除选择列表,并在每次单击按钮时用不同的数字重新填充它.

which populates a dropdown with 7 items. I could have an "item-3" which would populate a dropdown with three items. What I'm trying to do is select a button which could have an id value of "item-X" where X is the number of entries to populate so it could be different based on whatever button I click. I want to clear the select list and repopulate it with a different number on each button click.

这是我的代码:

 $('#items').empty();

 // alert('I was clicked, my id is ' + $(this).attr('id')); 
 var idnum = $(this).attr('id');
 var pos = idnum.lastIndexOf("-");
 var num = idnum.substring(pos + 1);

 // alert("You have " + num);

 // var numbers = [1, 2, 3, 4, 5]; 
 var numbers = new Array(num - 1);

 for (i = 0; i < num; i++) {
   numbers[i] = i + 1;
 }

 for (i=0;i<numbers.length;i++){ 
   $('<option/>').val(numbers[i]).html(numbers[i]).appendTo('#items'); 
 }

我尝试了empty()和remove(),但它们都不起作用.

I tried empty() and remove() and they're both not working.

推荐答案

$('#items').html('');

将清除您的选项.

这篇关于用jQuery动态填充下拉列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆