切换功能不适用于添加的输入

时间:2016-04-09 21:28:01

标签: javascript jquery html

切换功能在描述和示例中工作如图所示,但问题是当我通过用户输入添加新定义时它不起作用。请帮忙!

 <!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script>
$(document).ready(function(){

 $('.descrip').click(function(){
        $(this).next('.def').slideToggle("slow");
    });



});
function addDef () {
        //window.alert (1);
        var def= document.getElementById("defInput").value;  
       //window.alert (def);

       document.getElementById("addf").innerHTML += "<div class= 'descrip'> descrip </div>";
document.getElementById("addf").innerHTML += "<div class= 'def'> "+def+" </div>";
$(document).ready(function(){});
}
</script>
</head>
<body>

<div class = "descrip"> descrip</div>
<div class = "def"> example </div>
 enter def for apple: <input type= "text" id = "defInput"> </input> <br> <br>

<button onclick="addDef()">ADD</button>
<div id = "addf"> </div>

</body>
</html>

1 个答案:

答案 0 :(得分:0)

使用事件委托

  $(this).on("click", ".descrip", function() {
    $(this).next('.def').slideToggle("slow");
  });

<!DOCTYPE html>
<html>

<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
  <script>
    $(document).ready(function() {

      $(this).on("click", ".descrip", function() {
        $(this).next('.def').slideToggle("slow");
      });



    });

    function addDef() {
      //window.alert (1);
      var def = document.getElementById("defInput").value;
      //window.alert (def);

      document.getElementById("addf").innerHTML += "<div class= 'descrip'> descrip </div>";
      document.getElementById("addf").innerHTML += "<div class= 'def'> " + def + " </div>";

    }
  </script>
</head>

<body>

  <div class="descrip">descrip</div>
  <div class="def">example</div>
  enter def for apple:
  <input type="text" id="defInput">
  <br>
  <br>

  <button onclick="addDef()">ADD</button>
  <div id="addf"></div>

</body>

</html>