简体   繁体   中英

jQuery: How to differ multiple same buttons and pass parameter?

I try to move this working solution to jQuery.

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

....

function foo (x)
{
}

How can I do this the jQuery way? Is it a good idea to do so?

I tried this but I do not know how to get the parameter ${l} into the function also how to differ the differnt buttons.

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

...

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

Fix your HTML to look like:

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

Then in jQuery use:

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

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

If you need some other text for the button other than ${l} , use a 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM