jquery .click() 在按钮(单击)和文本在 for 循环中运行时不显示预期的文本。按钮和文本均由其 class 引用

jquery .click() doesn't display the expected text while button (clicked) and text runs in a for loop. Both button and text is referred by their class

我正在使用控制器 (Spring-boot) 并将数据注入 JSP 页面。 TextONE 和 TextTWO 是控制器注入 JSP 页面的数据。

在 Jsp 中,我是 运行 一个 for 循环,其中包含按钮和文本 (h3)。现在,当我单击任何按钮时,会出现 TextONE,这很奇怪。我的要求是单击第二个按钮时应该出现 TextTWO。为什么会发生这种情况,我该如何实现。

部分控制器代码

    @GetMapping("")
    public String showHome(Model theModel) {

         List<String> myList = new ArrayList<>();
         myList.add("Text ONE");
         myList.add("Text TWO");

         theModel.addAttribute("mylist",myList);

         return "home";
   }

JSP 和 Jquery 代码

<c:forEach var="item" items ="${mylist}"> // mylist here holds TextONE and TextTWO

   <h3 class="text">${item}</h3>
   <button class="click">Click Me</button>

</c:forEach>



<script>

  $(document).ready(function(){


       $(".click").click(function(){


    var result = $(".text").html();
    alert(result + " is the result");

    console.log(result);

   });



 });

</script>

在任意按钮上单击两个按钮,我得到相同的文本,即下图所示的“文本一”

请为每个按钮和 h3 标签使用唯一的 class 名称。

在您的代码中 $(".text").html() 将始终 return html 来自使用 class "text" 的第一个元素.

或使用下面

$(".click").click(函数(){

var result = $(this).prev().html();
alert(result + " is the result");

console.log(result);

});

(this) 表示您点击的按钮。当前触发事件的对象

一个简单的解决方案是, 发送列表计数模型 喜欢 theModel.addAttribute("size", myList.size());

然后创建一个元素输入来保存列表大小 <input type="hidden" value="{size}" id="count"/>

将 id 添加到列表元素[文本并单击]

在您的 JS 代码中, 获取列表大小 let size = $('#count').value;

循环你的 onClick 函数

for(let i = 0; i < size; i++){
$("#click"+i).click(function(){

    var result = $("#text"+i).html();
    alert(result + " is the result");

    console.log(result);
     }); }

另一个解决方案是查找被点击列表的父元素和select它的 h3 子元素

[此处示例]https://www.geeksforgeeks.org/jquery-parent-parents-with-examples/