我有一个评论列表现在我想向大家发送回复,我在输入表单中使用了这段代码:
@foreach($comments as $comment)
<div class="questions" dir="rtl">
{{$comment->description}}
<div class="row">
<div class="col-sm-2">
<input type="hidden" value="{{$comment->id}}"
class="comment_id">
<button type="submit" style="float:right"
class="send_answer"> send </button>
{{csrf_field()}}
</div>
<div class="col-sm-10">
<input class="answer" type="text" />
</div>
</div>
</div>
@endforeach
现在我在ajax中使用此代码但是我在控制台中给出了未定义的错误:
$(document).on('click', '.send_answer', function (event) {
var comment_id = $(this).find('.comment_id').val();
var answer = $(this).find('.answer').val();
console.log(comment_id);
console.log(answer);
});
我如何给出Comment_id并发送给ajax?
答案 0 :(得分:0)
使用parent()
或prev()
获取jquery中的comment_id
$(document).on('click', '.send_answer', function (event) {
var comment_id = $(this).parent().find('.comment_id').val();
var answer = $(this).closest('.questions').find('.answer').val();
console.log(comment_id);
console.log(answer);
});
答案 1 :(得分:0)
您可以使用closest()
,parent()
和个人元素id
和class
:
$(document).on('click', '.send_answer', function (event) {
var comment_id = $(this).closest('.questions').find('.comment_id').val();
var answer = $(this).closest('.questions').find('.answer').val();
console.log(comment_id);
console.log(answer);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="questions" dir="rtl">
<div class="row">
<div class="col-sm-2">
<input type="text" value="121"
class="comment_id">
<button type="submit" style="float:right"
class="send_answer"> send </button>
</div>
<div class="col-sm-10">
<input class="answer" type="text" value='answer' />
</div>
</div>
</div>