javascript - 单击按钮并返回值时重复多级下拉菜单

标签 javascript html

这里是设置。我的初始页面上有两个彼此相邻的下拉菜单。第二个下拉列表中的值取决于第一个下拉列表中的值。这工作得很好。

我有一个“添加”按钮,它可以复制下拉列表行,即在之前的下拉列表下方添加 2 个相邻的下拉列表。

添加下拉菜单效果很好。但是,如果我在初始下拉列表中选择了一个值,并且在第二个下拉列表中加载了相应的值(取决于第一个下拉列表中的值),则相同的值将在新添加的下拉列表中重复。

此外,新添加的下拉列表不响应,即左侧下拉列表的更改不会更改右侧下拉列表中的值。 (响应能力仅在最初添加的下拉列表中)

也许我没有使用最好的 JavaScript 实践,请原谅我,因为我对此很陌生。

欢迎任何反馈。谢谢。

代码如下:

<div class="container">
        <table id="myTable">
                <tr id="initialRow" class="select_row">



<td>
        <select  id= "select1" class = "select1">
                <option>Select an option</option>
                <option>yes</option>
                <option>no</option>
              </select>

                <select  id = 'select2' class = "select2">
                </select>

</td>

</tr>
</table>
<button class = "button" type="button" onClick ="addRow()">Add</button>
<button class = "button" type="button" onClick ="getValues()">Print values</button>
</div>

<script>
    const table = document.querySelector('#myTable');
    const rowToDuplicate = document.querySelector('#initialRow');
    function addRow() { 
      var duplicate = rowToDuplicate.cloneNode(true);
   duplicate.removeAttribute('id');      table.appendChild(duplicate);
    }

    function getValues() {
      const rows = document.querySelectorAll('.select_row');
     rows.forEach((row, i) => {
       console.log(`row ${i}: select1 `, row.querySelector('.select1').value);   console.log(`row ${i}: select2 `,row.querySelector('.select2').value);
     })

    }
</script>


<script>
        (function() {

            //setup an object fully of arrays
            //alternativly it could be something like
            //{"yes":[{value:sweet, text:Sweet}.....]}
            //so you could set the label of the option tag something different than the name
            var bOptions = {
              "yes": ["sweet", "wohoo", "yay"],
              "no": ["you suck!", "common son"]
            };

            var A = document.getElementById('select1');
            var B = document.getElementById('select2');

            //on change is a good event for this because you are guarenteed the value is different
            A.onchange = function() {
              //clear out B
              B.length = 0;
              //get the selected value from A
              var _val = this.options[this.selectedIndex].value;
              //loop through bOption at the selected value
              for (var i in bOptions[_val]) {
                //create option tag
                var op = document.createElement('option');
                //set its value
                op.value = bOptions[_val][i];
                //set the display label
                op.text = bOptions[_val][i];
                //append it to B
                B.appendChild(op);
              }
            };
            //fire this to update B on load
            A.onchange();

          })();
      </script>

最佳答案

几件事:

  1. 脚本标记中的代码运行一次。这意味着您只需初始化一次选择。您动态添加的那些选择不会初始化,并且不会对 onchange 事件使用react。
  2. 您的克隆还不够。您需要克隆 clean 行,然后继续克隆该行。
  3. 您过于依赖ids。一旦你开始处理新的动态行,这些 id 就会很痛苦。

我做了一个快速修复,应该可以帮助您继续。让我知道这是否有帮助。

<div class="container">
  <table id="myTable">
    <tr id="initialRow" class="select_row">
      <td>
        <select class="select1">
          <option>Select an option</option>
          <option>yes</option>
          <option>no</option>
        </select>
        <select class="select2"></select>
      </td>
    </tr>
  </table>
  <button class="button" type="button" onClick="addRow()">Add</button>
  <button class="button" type="button" onClick="getValues()">Print values</button>
</div>

<script>
  const table = document.getElementById('myTable');
	const initialRow = document.getElementById('initialRow');
  const rowToDuplicate = initialRow.cloneNode(true);

  function addRow() {
     let duplicate = rowToDuplicate.cloneNode(true);	
     let select1 = duplicate.lastElementChild.firstElementChild
     let select2 = duplicate.lastElementChild.lastElementChild		

     select1.setAttribute('id', 'select1-' + table.children.length)
     select2.setAttribute('id', 'select2-' + table.children.length)

     table.appendChild(duplicate);
     initSelects(select1, select2);
  }

  function getValues() {
    const rows = document.querySelectorAll('.select_row');
    rows.forEach((row, i) => {
      console.log(`row ${i}: select1 `, row.querySelector('.select1').value);
      console.log(`row ${i}: select2 `, row.querySelector('.select2').value);
    })
  }
	
	function initSelects(a, b) {
		var bOptions = {
      "yes": ["sweet", "wohoo", "yay"],
      "no": ["you suck!", "common son"]
    };

		a.onchange = function () {
			//clear out B
			b.length = 0;
			//get the selected value from A
			var _val = this.options[this.selectedIndex].value;
			//loop through bOption at the selected value
			for (var i in bOptions[_val]) {
				//create option tag
				var op = document.createElement('option');
				//set its value
				op.value = bOptions[_val][i];
				//set the display label
				op.text = bOptions[_val][i];
				//append it to B
				b.appendChild(op);
				}
		}
	}
	
	initSelects(
		initialRow.lastElementChild.firstElementChild, 
		initialRow.lastElementChild.lastElementChild
	);
</script>

关于javascript - 单击按钮并返回值时重复多级下拉菜单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51575218/

相关文章:

javascript - 使用 Javascript AJAX(不是 jQuery)提交嵌入式 Mailchimp 表单

javascript - Node.js - 在继续之前从 MySQL 获取返回值

javascript - 表单操作无法正常工作。它不会移动到指令链接,即 < form action ="">

javascript - 将 Google 自动完成功能添加到 Google 搜索栏?

html - css 位置固定在区域内的某个位置

javascript - 在 Django 中显示来自 API 的 JSON 数据

javascript - 线性分区,完美图片库

javascript - 在 jQuery 中添加新行时禁用其他选择框的选定选项

html - CSS 将两个具有相对宽度的 div 并排放置

javascript - 使用 Javascript 和 API 访问 Google Analytics 数据的问题