Jquery点击动态元素

时间:2017-10-20 21:29:43

标签: jquery html ajax

我在我的网站上有一个upvote帖子样式布局,我有一个加载更多帖子的ajax请求,该代码工作正常,但我的问题是当我尝试upvote他们。 那些不是从ajax请求中动态显示的那些可以被投票,但是当它加载更多时,它们就不能被投票。

我有一个ID like_postID,因此代码可以检查帖子是否正在被投票。

搜索我遇到了$(document).on( eventName, selector, function(){} );,我尝试了它仍然有效,但只有ajax调用没有请求的那些。

继承我的HTML代码:

<div class="contain">
  <div class="upvote-vetor">
    <a href="javascript:void(0)"><img alt="" src="images/upvotes.png" id="like_'.$post['id_post'].'" class="like"></a>
    <p id="likes_'.$post['id_post'].'">'.$upvote['upvotes'].' Up Votes</p>
 </div>

继承我的Jquery:

$(document).ready(function(){

    // like and unlike click
    $(".upvote-vetor").on("click",".like", function(){
        var id = this.id;   // Getting Button id
        var split_id = id.split("_");

        var text = split_id[0];
        var postid = split_id[1];  // postid
        // Finding click type
        var type = 1;
        // AJAX Request
        $.ajax({
            url: 'php/upvote.php',
            type: 'post',
            data: {postid:postid,type:type},
            dataType: 'json',
            success: function(data){
                var likes = data['likes'];

                $("#likes_"+postid).text(likes);        // setting likes

            },
            error: function(data){
                alert("error : " + JSON.stringify(data));
            }
        });
    });
});

PHP upvote代码:

$userid = $id_user;
$postid = $_POST['postid'];


// Check entry within table
$query = "SELECT COUNT(*) AS upvotes FROM upvotes WHERE id_post='$postid' and id_user= '$userid'";

$result = $conn->prepare($query);
$result->execute();
$fetchdata = $result->fetch(PDO::FETCH_ASSOC);
$count = $fetchdata['upvotes'];


if($count == 0){
    $insertquery = $conn->prepare("INSERT INTO `upvotes` (`id_upvote`, `id_user`, `id_post`) VALUES (NULL, '$id_user', '$postid');");
    $insertquery ->execute();
}else {

    $updatequery = $conn->prepare("DELETE FROM `upvotes` WHERE   id_user= '$userid' and id_post='$postid'");
    $updatequery->execute();
}


// count numbers of like and unlike in post
$query2 = "SELECT COUNT(*) AS upvotes FROM upvotes WHERE id_post='$postid'";
$result2 = $conn->prepare($query2);
$result2->execute();
$fetchlikes = $result2->fetch(PDO::FETCH_ASSOC);
$totalLikes = $fetchlikes['upvotes']. " Up Votes";


$return_arr = array("likes"=>$totalLikes);

echo json_encode($return_arr);

提前致谢。 :)

1 个答案:

答案 0 :(得分:1)

您需要将侦听器附加到已存在的父元素,以侦听相关元素的单击。例如:

$('body').on('click','.upvote-vetor .like', my_function)