2016-05-16 28 views
3

我帶班格時=「投票」是如何選擇一個類或ID的按鈕被點擊使用jQuery

<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頁面上幾個這種類型的申報單,

我與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');} 

我newbee,我的問題是,當一個downvote按鈕點擊(頁面上有幾個downvote按鈕)如何爲class =「vote」的相應div選擇ID =「q_id」或class =「q_id」的輸入標籤,並通過ajax數據傳遞其值。

+0

你的意思是你要發佈通過ajax輸入數據到url?並作爲回報,你想獲得任何數據或不? –

+0

你應該添加'event.preventDefault();'到你的JS代碼,以防止表單提交,並且你沒有使用表單來完成它。所以使它也形成..! –

+0

您的投票類div只包含2個元素嗎? –

回答

4

一種方法是讓父元素(這是投票的div),然後發現裏面的q_id元素:

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

這裏有一個快速小提琴: https://jsfiddle.net/1m56g6jL/

+0

謝謝@James Waddington它的工作! – javed

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... 

}); 
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> 
相關問題