weixin_33717298 2014-11-25 12:31 采纳率: 0%
浏览 13

jQuery div和类冲突

I'm having some trouble with my jquery ajax code. I have 2 functions, one that will submit a value and other that will update the values in real time.. At least that's what it is supposed to do. :P

So, I have a list that is created throught some PHP code:

<div id="votos">
    <ul class="yourvotes">Your votes: 0</ul>
    <li class="votesofothers">
        <a href="#" class="votar" id="3124" iduser="3124" rel="Votar">User</a>  Votes: (0)</br>
        <a href="#" class="votar" id="3125" iduser="3125" rel="Votar">User2</a>  Votes: (0)</br>
    </li>
    </ul>
</div>

And then I have a Ajax call to update the database when one of the links is pressed:

$(function(){
    $('.votar').click(function(){
        var elem = $(this);
        $.ajax({
            type: "GET",
            url: "votar.php",
            data: "id="+elem.attr('iduser'),
            dataType:"json",  
            success: function() {
                window.location.reload(true);
            }
        });
        $(document).ajaxStop(function(){
            window.location.reload();
        });
        return false;
    });
});

And this would be the code to update the values that appear in "real-time":

function mostrarvotos() {
    $('#votos').load('votos.php');
    setTimeout('mostrarvotos()',1000);
}
mostrarvotos();

(I originally wanted to update each of the user votes instead of updating the whole div but I couldn't manage to do it.)

So my problem is that when I add the "mostrarvotos()" function to my code the links stop working and just add a # to the url, but if I remove it everything works fine.. If you could help me with this I would greatly appreciate.

  • 写回答

2条回答 默认 最新

  • weixin_33738555 2014-11-25 12:37
    关注

    That's because you are not prevent the link's original action. The click handler won't catch the event when you refreshed the content with an AJAX request. Try document.on instead of your current handler:

    $(document).on('click','.votar',function(e){
        e.preventDefault(); //Prevent the default action
        var elem = $(this);
        $.ajax({
            type: "GET",
            url: "votar.php",
            data: "id="+elem.attr('iduser'),
            dataType:"json",  
            success: function() {
                window.location.reload(true);
            }
        });
        $(document).ajaxStop(function(){
            window.location.reload();
        });
        return false;
    });
    

    Also note the preventDefault which prevents the defauls link action (the # in your address bar).

    评论

报告相同问题?