开发者

converting function to jquery click() call

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜