【问题标题】:How to get the value of a cloned option select menu?如何获取克隆选项选择菜单的值?
【发布时间】:2021-09-08 21:43:29
【问题描述】:

我在 html 中有一个带有“选择选项”的非常大的下拉菜单。因为我想多次使用这个菜单,所以我想通过使用 jQuery “clone and appendTo”来复制下拉菜单。

但是如何获取克隆的下拉菜单的值呢?这是我尝试过的。它让我返回 selectedValueCar2 的“未定义”

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>



  <p>first box here:</p>
  <select id="list1" onchange="fn1();">
    <option value ="car1000">Audi A2 (2001)</option>
    <option value ="car1010">Audi A3 (2004)</option>
    <option value ="car1020">Audi A5 (2009)</option>
  </select>
  
  <div id="list2"><p>second box here:</p></div>
  <script>
    $( "#list1" ).clone().appendTo( "#list2");
  </script>

<script>
  function fn1(){
selectedValueCar = document.getElementById("list1").value;
        console.log(selectedValueCar);
selectedValueCar2 = document.getElementById("list2").value;
        console.log(selectedValueCar2);
  }
</script>

</body>
</html>

【问题讨论】:

    标签: javascript jquery append clone html-select


    【解决方案1】:

    非常感谢。我现在的解决方案是,在克隆时更改 ID 属性。

      <div id="list2"><p>second box here:</p></div>
      <script>
        $("#list1").clone().attr("id","list5").appendTo("#list2");
      </script>
    

    【讨论】:

      【解决方案2】:

      如果您在浏览器中打开该页面并检查它,您会发现问题所在。

      它将整个&lt;select id="list1"&gt;...&lt;/select&gt; 克隆到&lt;select id="list2"&gt; 而不仅仅是&lt;option&gt; 标签。所以document.getElementById("list2").value 没有价值(&lt;option value="xxx"&gt;),所以你会看到“未定义”

      HTML view after clone

      【讨论】:

        【解决方案3】:

        为了“克隆”html元素,你必须得到它的Html。然后将其加载到变量中,以便您可以在其他地方将其用作 html。看看我的例子:

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2012-08-03
          • 1970-01-01
          • 2010-10-19
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多