doumengwei0138
doumengwei0138
2015-10-15 10:29

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 dongxi0523 6年前

    Try to remove your listener before you add it:

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

    And

    $(".content").off('click');
    $(".content").click(function(){...}
    
    点赞 评论 复制链接分享
  • dskm94301 dskm94301 6年前

    You are getting two alerts because you are returning twice the click handler with the .post response.

    Basically with each additional submit you will get an additional alert.

    Remove your click handler from the POST response and attach the event to the body so it can handle dynamically added elements.

    add this into your main <script> section:

    $('body').on('click', '.content', function() {
        alert("i've been clicked once");
    });
    

    and your php file will be only this:

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

    without the need to load jquery or outputting any javascript

    点赞 评论 复制链接分享

为你推荐