jQuery:如何区分多个相同的按钮并传递参数?

luaexgnf  于 2023-01-25  发布在  jQuery
关注(0)|答案(1)|浏览(100)

我尝试将这个可行的解决方案转移到jQuery。

<table>
    <tr th:each="l : ${lst}">
        <td>
            <input type="button" th:onclick="foo ([[${l}]])"/>
        </td>
    </tr>
</table>

....

function foo (x)
{
}

我怎样才能用jQuery的方式来做呢?这样做好吗?
我尝试了这个方法,但我不知道如何将参数${l}导入函数,也不知道如何区分不同的按钮。

<table>
    <tr th:each="l : ${lst}">
        <td>
            <input type="button" id="mybutton"/>
        </td>
    </tr>
</table>

...

$("#mybutton").click (function ()
{
});
vltsax25

vltsax251#

将HTML修改为如下所示:

<table>
  <tr th:each="l : ${lst}">
    <td>
      <input class="mybutton" type="button" value="${l}">
      <!-- Fix the above's ${l} to be the desired output value -->
    </td>
  </tr>
</table>

然后在jQuery中用途:

function foo () {
  // Do something 
  console.log(this.value); // whatever is returned by `${l}`
};

$("table").on("click", ".mybutton", foo);

如果需要${l}以外的其他文本,请使用HTMLButtonElement:

<table>
  <tr th:each="l : ${lst}">
    <td>
      <button class="mybutton" type="button" value="${l}">Click me!</button>
      <!-- Fix the above's ${l} to be the desired output value -->
    </td>
  </tr>
</table>

相关问题