如何在动态生成的列表中使用按钮更改文本?

How to change a text with a button in a dynamically generated list?

我使用 play framework 2.3.8,我正在尝试更改按钮旁边的某个文本值。该按钮是通过生成的列表动态添加的,因此我无法找到按钮旁边的正确文本。

这是它的样子:

我的视图 class 得到了一个问题列表 questionList: List[Question] 我对其进行迭代并将一堆按钮放入我的 html:

@for(question <- questionList){
<!-- Questions -->
<li class="list-group-item" >
<button type="button" class="btn btn-default"  id="upvoteButton" 
value="voteUp" style="width: 30px; height: 30px; text-align: center; vertical-align: center;">
<span class="glyphicon glyphicon-arrow-up" aria-hidden="true" style="color:orange"></span>
</button>

<span class="num"> @question.voteScore </span>

(...)

在 class "num" 中是我想通过单击按钮更改的问题的实际投票分数。 id-tag 没有帮助,因为生成的按钮因此都具有相同的 id-tag(旁注:只有第一个 id 实际有效,我猜第一个按钮获得唯一 id?)。

目前我的方法:

如果我单击 num 本身,我可以更改它的值:

$(document).ready(function(){
            $(document).on('click', '.num', function(){
                $(this).html(111);
                });
        });

但是尝试通过单击按钮来完成此操作失败了:

$(document).ready(function(){
    $(".btn-default").click(function(){
        $(this).slideUp().slideDown();
        console.log($('.num').html());
    });
});

无论我点击哪个按钮,console.log的输出总是76。我找不到链接到正确号码的按钮。我该如何实现?

试试这个:-

$(".btn-default").click(function(){
    $(this).slideUp().slideDown();
    $(this).next('.num').html('111');
});

或者您也可以尝试:-

 $(".btn-default").click(function(){
    $(this).slideUp().slideDown();
    $(this).parent('li').find('.num').html('111');
});

我认为当你进行 document.ready init 调用时你的按钮不是 'visible' 所以我建议以这种方式添加它,使其生效或绑定到 dom动态通话结束后..

$(document).ready(function(){
    $('body').on( 'click', '.btn-default' , function(){
        $(this).slideUp().slideDown();
        console.log($('.num').html());
    });
});

h, k