将函数转换为jquery click()调用

时间:2011-07-19 15:09:18

标签: javascript jquery

以下是我要转换的代码:

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

如何将其转换为:

$('button').click(function() { .... } );

其中{{rowid}}是动态生成的,每行都是唯一的?

4 个答案:

答案 0 :(得分:2)

如果使用data-属性存储id,则可以在单击该元素时将其从元素中删除。

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

答案 1 :(得分:2)

我可能会将按钮更改为:

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

然后使用类似这样的jQuery:

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

答案 2 :(得分:1)

可能的解决方案

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

答案 3 :(得分:0)

您可以将{{row id}}指定给每个按钮作为属性,然后在方法中阅读:

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

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