![](/img/trans.png)
[英]How can I get the value of a control whose ID was passed to javascript function from code behind
[英]How to get the value of an HTML control whose ID changes dynamically? (in JavaScript)
我是JavaScript新手,只停留在一点。 需要你的帮助。
我有2个下拉菜单,不是正常的“选择”下拉菜单,而是借助无序列表和CSS进行的。 就像是:
下拉菜单1:
<ul class="dropdown-menu" min-width: 180px;">
@foreach(Fruit item in Fruits)
{
<li><a id="@("FR_" + @item.FruitID)" onClick="RefreshPullDown(this.id)">@item.FruitName</a></li>
}
</ul>
下拉菜单2:
<ul class="dropdown-menu" min-width: 180px;">
@foreach(Vedgetable item in Vegetables)
{
<li><a id="@("VEG_" + @item.VegetableId)" onClick="RefreshPullDown(this.id)">@item.VegetableName</a></li>
}
</ul>
如您所见,在两个下拉列表中,ID都是动态生成的。 现在,我的目标是基于下拉列表1和下拉列表2的选定值填充表。如果用户更改了两个下拉列表中任何一个的值,则我的表应使用新值填充,其中包含DD1和DD2。 我尝试了以下Javascript函数(当下拉列表1的值更改时):
Javascript:
function RefreshPullDownValue(anchorId) {
var fruitAnchorId;
var vegAnchorId;
if (anchorId.indexOf('FR') >= 0) {
fruitAnchorId = anchorId;
}
else {
VegAnchorId = anchorId;
}
var fruitValue = &('#' + fruitAnchorId).text();
//How to fetch the other dropdown value here??
// code to call controller and get the table populated..
}
这里的问题是我可以获取被单击的列表项的值。 我想如何获得同时在另一个DD中选择的值,因为它的ID是动态的并且不是固定的。我需要在一个JS函数中同时获得两个下拉值,然后才能继续。 任何帮助,将不胜感激。
您可以在类似这样的点击中存储值。
<li><a id="@("VEG_" + @item.VegetableId)" onClick="StorePullDownValue(this.id, 'first')">...</li>
第二个下拉菜单
<li><a id="@("VEG_" + @item.VegetableId)" onClick="StorePullDownValue(this.id, 'second')">...</li>
在你的js中
var dd1 = null,
dd2 = null;
var StorePullDownValue = function(value,type){
if(type == "first"){
dd1 = value;
}else{
dd2 = value;
}
if(dd1 != null && dd2 != null){
// call your function here to generate a table
}
}
您还可以使用jquery简化代码并使之更好。
在第一个DD中,ID与“ FR__”串联
id="@("FR_" + @item.VegetableId)"
在第二个DD中,ID与“ VEG_”串联
id="@("VEG_" + @item.FruitID)"
因此,您已经知道何时执行此操作:
if (anchorId.indexOf('FR') >= 0) {
fruitAnchorId = anchorId;
//first DD
}
else {
VegAnchorId = anchorId;
//second DD
}
您可以通过像这样@Nehal在jquery中更改代码来实现此目的
的HTML
// Dropdown 1
<ul class="dropdown-menu" style="min-width: 180px;">
@foreach(Fruit item in Fruits)
{
<li><a id="@("FR_" + @item.FruitID)" class="fruitItem">@item.FruitName</a></li>
}
</ul>
// Dropdown 2
<ul class="dropdown-menu" style="min-width: 180px;">
@foreach(Vedgetable item in Vegetables)
{
<li><a id="@("VEG_" + @item.VegetableId)" class="vegItem">@item.VegetableName</a></li>
}
</ul>
jQuery的
$('a.vegItem').on('click', function (event)
{
var VegSelection= $(this).text();
alert(VegSelection);
});
$('a.fruitItem').on('click', function (event)
{
var FruitSelection= $(this).text();
alert(FruitSelection);
});
查看此小提琴以进行理解。 希望这对您有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.