문제

등급 시스템을 만들고 있으며 INdex.php 페이지에 다음 jQuery 코드가 있습니다.

<script type="text/javascript">

$(document).ready(function() {

    $("[id^=rating_]").hover(function() {

        var rid = $(this).attr("id").split("_")[1];
        $("#rating_"+rid).children("[class^=star_]").children('img').hover(function() {

            $("#rating_"+rid).children("[class^=star_]").children('img').removeClass("hover");

            /* The hovered item number */
            var hovered = $(this).parent().attr("class").split("_")[1];
            var hovered2 = $(this).parent().attr("class").split("_")[1];

            while(hovered > 0) {
                $("#rating_"+rid).children(".star_"+hovered).children('img').addClass("hover");
                hovered--;
            }

            $("#rating_"+rid).children("[class^=star_]").click(function() {
                var current_star = $(this).attr("class").split("_")[1];

                $.post("send.php", {rating: current_star, id: rid});
            });
        });

    });




});

</script>

기본적으로 호버 효과가 발생한 다음 별을 클릭하면 게시물 요청을 보내고 송신. 이 스크립트 아래에는 다음과 같은 PHP가 있습니다.

<?php


$query = mysql_query("SELECT * FROM test");

while($row = mysql_fetch_array($query)) {
    $rating = (int)$row[rating];
    ?>
    <div id="rating_<?php echo $row[id]; ?>">
    <span class="star_1"><img src="star_blank.png" alt="" <?php if($rating > 0) { echo"class='hover'"; } ?> /></span>
    <span class="star_2"><img src="star_blank.png" alt="" <?php if($rating > 1.5) { echo"class='hover'"; } ?> /></span>
    <span class="star_3"><img src="star_blank.png" alt="" <?php if($rating > 2.5) { echo"class='hover'"; } ?> /></span>
    <span class="star_4"><img src="star_blank.png" alt="" <?php if($rating > 3.5) { echo"class='hover'"; } ?> /></span>
    <span class="star_5"><img src="star_blank.png" alt="" <?php if($rating > 4.5) { echo"class='hover'"; } ?> /></span>
    <div class="clearleft">&nbsp;</div>
    </div>
    <br />
    <?php   
}

?>

그리고 물론 나는 그것을 멋지게 만들기 위해 몇 가지 CSS를 가지고 있습니다.

send.php 파일은 다음과 같습니다.

<?php

mysql_connect("localhost", "admin", "") or die(mysql_error());
mysql_select_db("test") or die(mysql_error());


$rating = (int)$_POST['rating'];
$id = (int)$_POST['rid'];



$query = mysql_query("SELECT * FROM test WHERE id = '".$id."'") or die(mysql_error());

while($row = mysql_fetch_array($query)) {

    if($rating > 5 || $rating < 1) {
        echo"Rating can't be below 1 or more than 5";
    }
    else {

        $total_ratings = $row['total_ratings'];
        $total_rating = $row['total_rating'];
        $current_rating = $row['rating'];

        $new_total_rating = $total_rating + $rating;
        $new_total_ratings = $total_ratings + 1;
        $new_rating = $new_total_rating / $new_total_ratings;


        // Lets run the queries. 

        mysql_query("UPDATE test SET total_rating = '".$new_total_rating."' WHERE id = '".$id."'") or die(mysql_error());
        mysql_query("UPDATE test SET rating = '".$new_rating."' WHERE id = '".$id."'") or die(mysql_error());
        mysql_query("UPDATE test SET total_ratings = '".$new_total_ratings."' WHERE id = '".$id."'") or die(mysql_error());
    }

}




?>

데이터베이스 테이블에는 3 개의 등급 열이 있습니다. Total_rating : 총 등급 (모든 등급이 함께 추가). 등급 : 현재 등급 Total_ratings : 등급 금액.

문제는 $ _post [ 'rating'] 및 $ _post [ 'rid']를 $ _get으로 변경하고 int int int, 예를 들어, send.php? id = 1 & rate = 4를 넣으면 작동한다는 것입니다. 데이터베이스가 업데이트됩니다. 그러나 별을 누르면 데이터베이스가 업데이트되지 않습니다. 스크립트를 엉망으로 한 후 게시물이 작동해야한다는 것을 깨달았지만 ID는 0으로 반환됩니다.

이것을 더 테스트하기 위해 이것을 클릭 함수에 넣습니다.

document.write(current_star+rid);

반환 된 것을보기 위해. 문제는 반환 된 숫자에 요소 위에 떠오르는 횟수를 곱한 것 같습니다. 그래서 내가 아마도 6 개의 별을 맴돌 으면 current_star와 id는 6 번 반복됩니다.

나는 이것을 일하기에 너무 가까이있는 것 같아, 아무도 그것에 무슨 일이 일어나고 있는지 아는 사람이 있습니까? 미리 감사드립니다.

도움이 되었습니까?

해결책

jQuery의 이벤트 처리에 대해 실현하는 데 중요한 것은 레지스트리 기반이라는 것입니다. 다수의 특정 이벤트에 대한 콜백은 그들이 구속 된 순서대로 호출됩니다.

당신이보고있는 이유는 반복됩니다 current_star 그리고 id 값은 모든 호버에서 점점 더 많은 이벤트를 계속 바인딩하기 때문입니다. 이것은 당신의 것이기 때문입니다 click() 당신의 안에 전화하십시오 hover() 따라서 호버 할 때마다 다른 Click () 이벤트를 바인딩합니다.

당신의 구속을 시도하십시오 click() 호버 이벤트 밖에서 이벤트를 사용하여 다음과 같은 것을 사용합니다.

$("[id^=rating_]").children("[class^=star_]").click(function() {
        var rid = $(this).parent().attr("id").split("_")[1];
        var current_star = $(this).attr("class").split("_")[1];

        $.post("send.php", {rating: current_star, id: rid});
});

당신은 또한 하나를 묶고 싶지 않을 것입니다 hover() 같은 이유로 다른 사람 안으로 전화하십시오.

다른 팁

나는 당신이 사용한 것을 보았습니다 $_POST['rid'] 대신에 $_POST['id']. 그게 당신의 문제 일 수 있습니다.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top