我如何重复HTML中的选择元素 [英] How do I repeat select elements in HTML
问题描述
我在我的HTML页面中有一个选择/下拉菜单,它必须在页面中出现大约10次。简单的例子如下:
Qn 1:{dropdown}是{TextField}
Qn 2:{dropdown}是{TextField}
Qn 3:{dropdown}是{TextField}
其中,下拉菜单列出了相同和静态的各种选项(字符串数组 - 无服务器组件)。
我想创建一次下拉菜单并使用它。 CSS可以包含html的数据元素:select?或者如何编写javascript代码来填充select元素?
以下是一种方法(使用jQuery进行选择和遍历所有下拉菜单更容易):
< p> Qn 1:< select class =repeat>< / select> ;是{TextField}< / p>
< p> Qn 2:< select class =repeat>< / select>是{TextField}< / p>
< p> Qn 3:< select class =repeat>< / select>是一个{TextField}< / p>
<脚本类型= 文本/ JavaScript的 >
var optionOpen =< option>;
var optionClosed =< / option>;
var selectItems = [firstItem,secondItem, thirdItem];
$(。repeat)。each(function(){
for(key in selectItems)
{
$(this).append(optionOpen + selectItems [key] + optionClosed);
}
});
< / script>
我将选项格式化为一个列表,并将字符串连接起来以便更改和重用在页面之间。只需在 selectItems
列表中添加选项,即可将它们添加到类<$ c $ < select> 标记中C>重复。如果您需要表单分别处理它们,请为每个< select>
提供一个不同的名称
属性。
I have a select/drop down in my HTML page which has to appear about 10 times in the page. Simple sample for that would be as below:
Qn 1: {dropdown} is a {TextField}
Qn 2: {dropdown} is a {TextField}
Qn 3: {dropdown} is a {TextField}
Where dropdown lists various options which are same and static (array of strings - no server component).
I want to create the dropdown once and use it. Can CSS have data elements for the html:select? Or how do I write javascript code to fill the select elements?
Here's one way (using jQuery to make selecting and iterating through all dropdowns easier):
<p>Qn 1: <select class="repeat"></select> is a {TextField}</p>
<p>Qn 2: <select class="repeat"></select> is a {TextField}</p>
<p>Qn 3: <select class="repeat"></select> is a {TextField}</p>
<script type="text/javascript">
var optionOpen = "<option>";
var optionClosed = "</option>";
var selectItems = ["firstItem", "secondItem", "thirdItem"];
$(".repeat").each(function(){
for (key in selectItems)
{
$(this).append(optionOpen + selectItems[key] + optionClosed);
}
});
</script>
I formatted the select options as a list and concatenated the strings to make it easy to change and reuse between pages. Simply add options to the selectItems
list to add them to each <select>
tag with the class repeat
. Give each <select>
a different name
attribute if you need the form to process them separately.
这篇关于我如何重复HTML中的选择元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!