doumengwei0138 2015-10-15 10:29
浏览 204
已采纳

Javascript运行两次而不是一次

I have made the demo below to simplify my big problem, when enter "first input", click submit, click returned"first input", it alert once. However,refresh, when enter "first input",submit, then enter "second input",submit, click "first input", browser alert TWICE when intended to run once. What's the problem? How to fix this?

Html file (index.php)

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>

<input id="inputtext" type="text">
<button id="submit">Submit</button>
<div id="returned_result"></div>


<script>
$("#submit").click(function(){

    var content=$("#inputtext").val(); //get the value of input field

    $.post("testclick2.php", {content:content}, function(result){
    $("#returned_result").prepend(result);
     });

    $("#inputtext").val(""); //clear the input area

})

</script>

testclick2.php

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>

<?php
$content=$_POST["content"];
echo "<div class=\"content\">".$content."</div>"."<br>";
?>

<script>
$(".content").click(function(){
    alert("clicked");
})
</script>
  • 写回答

2条回答 默认 最新

  • dongxi0523 2015-10-15 10:34
    关注

    Try to remove your listener before you add it:

    $("#submit").off('click');
    $("#submit").click(function(){...}
    

    And

    $(".content").off('click');
    $(".content").click(function(){...}
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料