0

我试图通过 ajax 将一些数据传递给 php 文件,但前提是单击一个元素。

如何将每个 A 元素附加到相应的 JS 函数,并且只单击一次?

<a class="rating star1">1</a><br />
<a class="rating star2">2</a><br />
<a class="rating star3">3</a><br />

<script>
//CANT WORK OUT HOW TO ACTIVATE THIS FUNCTION ONLY IF .star1 IS CLICKED
function() { 
    $.post('/rate.php', {
    rating : '1', 
    page_id : '1234'
}, function(){
    });
}

//CANT WORK OUT HOW TO ACTIVATE THIS FUNCTION ONLY IF .star2 IS CLICKED
function() { 
    $.post('/rate.php', {
    rating : '2', 
    page_id : '1234'
}, function(){
    });
}

//CANT WORK OUT HOW TO ACTIVATE THIS FUNCTION ONLY IF .star3 IS CLICKED
function() { 
    $.post('/rate.php', {
    rating : '3', 
    page_id : '1234'
}, function(){
    });
}
</script>
4

2 回答 2

2

将 click 事件处理程序添加到具有 class 的所有元素rating。如果将 click 事件处理程序绑定到rating您可以消除一些重复的代码。

$(".rating").click(function(){
    $.post("/rate.php", {
        rating: $(this).html(), //will grab the rating from the html of clicked <a/>
        page_id: "1234"
    },function(){});
});
于 2013-09-24T08:58:16.857 回答
0

无需为每个链接提供功能

HTML

<a class="rating" data-rate="1" >1</a><br />
<a class="rating" data-rate="2">2</a><br />
<a class="rating" data-rate="3">3</a><br />

JS

$(document).ready(function(){
    $('.rating').click(function(){
        var rating_val = $(this).data('rate').val();
        $.post('/rate.php', {
            rating : rating_val, 
            page_id : '1234'
            }, function(){
        });        
    }
});
于 2013-09-24T09:04:29.143 回答