0

首先,如果可能的话,我想在没有 JQuery 和纯 Javascript 的情况下执行此操作。

好的,所以我有一个 html 表,其中的行被动态添加到其中。

在每一行是一个:

  • 选择元素 (id = "ddFields")
  • 文本输入元素 (id = "tfValue")
  • 按钮元素(无 id)

Button Element 删除它所在的行

选择元素有一个默认选项“”,然后是其他“有效”选项

文本输入已添加到该行,但它是隐藏的。

所有元素都在同一个

基本上,如果所选索引为 != 0,我希望 Select Element 显示隐藏的文本输入元素

到目前为止,我的 onchange 函数有这个:

function itemChanged(dropdown) //called from itemChanged(this)
{ 
   var cell         = dropdown.parentNode;
   var row      = cell.parentNode;
   var rowIndex = dropdown.parentNode.parentNode.rowIndex;
   var index            = dropdown.selectedIndex;
   var option           = dropdown.options[dropdown.selectedIndex].text;

   if(index >0)
   {    
     alert(row);
     var obj=row.getElementById("tfValue"); //tfValue is the Text Field element
     alert(obj);
     //row.getElementById("tfValue").hidden = "false"; //doesn't work
     //row.getElementById("tfValue").setAttribute("hidden","true"); //doesn't work
   }
   else
   {
      alert('none selected');

   }
}
4

2 回答 2

3

终于想通了。所以这里是:

场景: 动态添加行的表。

在每一行中都有一个选择元素和一个输入文本元素。

选择元素根据选择元素的索引更改输入文本元素的文本值。

在您的选择元素中,将 onchange 函数设置为:

onchange="selectionChanged(this)"

然后创建一个javascript函数,如下所示:

function selectionChanged(dropdown)
{
   //get the currently selected index of the dropdown
   var index     = dropdown.selectedIndex;

   //get the cell in which your dropdown is
   var cell      = dropdown.parentNode;located

   //get the row of that cell
   var row       = cell.parentNode;

   //get the array of all cells in that row 
   var cells     = row.getElementsByTagName("td");

   //my text-field is in the second cell
   //get the first input element in the second cell
   var textfield = cells[1].getElementsByTagName("input")[0]; 

   //i use the first option of the dropdown as a default option with no value
   if(index > 0)  
   {
      textfield.value = "anything-you-want";
   }
   else
   {
      textfield.value = null;
   }
}

希望这对任何人都有帮助。它困扰了我很长时间。感谢舒布的帮助!:)

于 2013-02-16T09:11:08.753 回答
1

首先,我希望你不要重复你的身份。没有两个项目应该具有相同的 id。

如果您正在迭代,请创建 id1、id2、id3。

此外,这不是必需的,但我建议像这样引入您的变量:

var a = x, 
    b = y,
    c = z;

如果你决定使用 jQuery,你可以这样做:

$('#tableid').on('click','button',function(){
    $(this).parent().parent().remove();
});

$('#tableid').on('change', 'select',function(){
    if($(this).val()){ $(this).next().show(); }
});

请务必更改#tableid 以匹配您的表的ID。

这假定文本输入是选择框之后的下一个元素。如果不是这样,请根据需要进行调整或询问,我将进行编辑。

于 2013-02-15T17:24:13.180 回答