开发者

converting function to jquery click() call

开发者 https://www.devze.com 2023-03-21 03:49 出处:网络
Here is the code that I\'m trying to convert: <script> function fsomething(rowid) { window.location = \"/somewhere/\" + rowid;

Here is the code that I'm trying to convert:

<script>
function fsomething(rowid) {
   window.location = "/somewhere/" + rowid;
}

</script>
<tr>
  <td>
      <button onClick="fsomething('{{rowid}}')">row 1L</button>
  </td>
  <td>
      <button onClick="fsomething('{{rowid}}')">row 2L</button>
  </td>
</tr>

How can I convert this to:

$('button').click(function() {开发者_Go百科 .... } );

where {{rowid}} is dynamically generated, and unique to each row?


If you store the id using a data- attribute then you can get that out of the element when it is clicked.

<script>

$(function(){

    $("td button").click(function(e){

        // Go to the URL
        window.location = "/somewhere/" + $(this).data("rowid");

        // Prevent default action if any
        e.preventDefault();

    });

});

</script>

<tr>
    <td>
        <button data-rowid="{{rowid}}">row 1L</button>
    </td>
    <td>
        <button data-rowid="{{rowid}}">row 2L</button>
    </td>
</tr>


I would probably change the buttons to something like this:

<button id="{{rowid}}">row 1L</button>

And then use jQuery something like this:

$("button").click(function() {
    window.location = "/somewhere/" + $(this).attr("id");
});


possible solution

$('button').click(function(event))
{
window.location = "/somewhere/" + $(event.target).attr('id');
}


You can assign the {{row id}} to each button as an attribute and then read it in the method:

<button rowid="{{rowid}}">row 1L</button>

$('button').click(function() { fsomething($(this).attr("rowid")); } );
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号