当使用jQuery时,如何在单击按钮时选择类或ID?

3

我带有 class="vote" 的 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="q_id"或class="q_id"的input标签,用于相应的class="vote" div,并通过ajax数据传递其值。


你的意思是想通过ajax将输入数据发布到URL上吗?并且作为回应,你是否想要获取任何数据? - Umair Shah Yousafzai
你应该在JS代码中添加event.preventDefault();以防止表单提交,同时你也没有使用表单来完成它..!所以也要将其变成表单..! - Umair Shah Yousafzai
@UmairShahYousafzai 嗯,这取决于情况。当不必要时,没有必要阻止默认行为。这样做会引起对被抑制的行为的质疑。因此,如果我作为开发人员后来加入,并且你已经无缘无故地散布了e.preventDefault(),那么对我来说,这会让事情变得混乱,因为我正在试图将该事件与实际不存在的东西联系起来。由于 OP 的 button 没有 action(即从我所看到的表单中),所以没有必要这样做。然而,如果 OP 的按钮确实提交了一个表单,那么你可能是正确的。 - mferly
@ Marcus:随你的便,朋友! :D - Umair Shah Yousafzai
只需记住,OP仅声明了一个div,而不是一个form。当包含在div中时,没有默认行为需要抑制 :) - mferly
显示剩余4条评论
3个回答

4

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

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

这里有一个快速的示例: https://jsfiddle.net/1m56g6jL/

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>

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

});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接