使用jquery

时间:2016-05-16 19:23:58

标签: javascript jquery html ajax

我的div与班级="投票"是

<div class="vote">
<input type="hidden" name="q_id" class="q_id" id="q_id" q_id="{{ result.object.id }}" value="{{ result.object.id }}">
<button type="submit" class="downvote" value="downvote">downvote</button>

在我的html页面上有几个这种类型的div,

我与jquery的ajax调用是

$('.downvote').click(function() {
var q_id=$(this).attr('q_id')
console.log(q_id)
$.ajax( {
    type: 'GET',
    url:"http://127.0.0.1:8000/q/downvote/",
    data:q_id,
    success: searchSuccessDown,
    dataType: 'html'
});
});
function searchSuccessDown(data) {
console.log('downvoted successfully');}

我是新手,我的问题是当点击一个downvote按钮时(页面上有几个downvote按钮)如何选择id =&#34; q_id&#34;或者类=&#34; q_id&#34;对于相应的div与class =&#34;投票&#34;并通过ajax数据传递其值。

3 个答案:

答案 0 :(得分:4)

一种方法是获取父元素(即投票div),然后在其中找到q_id元素:

var q_id = $(this).parent().find('.q_id').val();

这是一个快速的小提琴: https://jsfiddle.net/1m56g6jL/

答案 1 :(得分:1)

以下是您应该如何做到的:

HTML:

<div class="vote">
<form method="post" action="" id="downvote_form">
<input type="hidden" name="q_id" class="q_id" id="q_id" q_id="{{ result.object.id }}" value="{{ result.object.id }}">
<button type="submit" class="downvote" value="downvote">downvote</button>
</form>

JavaScript:

<script>
$(document).ready(function() {
        $('#downvote_form').on('submit', function(e) {
                $.ajax({
                        url: 'http://127.0.0.1:8000/q/downvote/',
                        data: $(this).serialize(),
                        type: 'POST',
                        success: function(data) {
                            if (data == "success") {
                                console.log(data);
                                window.location.href = "success.php"; //=== Show Success Message==
                            }
                        },
                        error: function(data) {
                            alert("You have an error); //===Show Error Message====
                            }
                        }); e.preventDefault(); //=== To Avoid Page Refresh and Fire the Event "Click"===
                });
        });
</script>

答案 2 :(得分:0)

这样做:

...click(function (e) {

var qIdNode = $(e.target)
.closest(".vote") // navigates to the closest parent that have the class vote
.find('.q_id'); // then finds the sibling q_id element of the target/clicked element...

});