点击DIV或A标签激活JS功能

时间:2013-09-24 08:55:20

标签: javascript ajax

我试图通过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>

2 个答案:

答案 0 :(得分:2)

为具有类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(){});
});

答案 1 :(得分: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(){
        });        
    }
});