jQuery中的表上的Click事件 [英] Click event on table in jQuery

查看:78
本文介绍了jQuery中的表上的Click事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有html,我需要在表中动态添加一行,还需要在append div类中捕获click事件.如何实现这个想法?

I have html, I need to append a row in a table dynamically, also I need to catch the click event in the append div class. How to achieve this any idea?

JavaScript:

JavaScript:

$(document).ready(function() {

    $("#click").click(function() {
        $('table').prepend('<tr> <td>something3</td> <td> <a><div class="s"> s </a> </td></tr>');
    });


    $(".s").click(function() {
        alert("Ok");
    });

});

HTML:

<input type="button" id="click" value="click"/>

<table width='100%'>
    <tr><td>something</td><td>else here</td></tr>
    <tr><td>something2</td><td>else here2</td></tr>
    <tr><td>something3</td><td>else here3</td></tr>
</table>

推荐答案

请参见 live() 方法,它允许您为DOM中与给定选择器匹配的所有当前和将来元素绑定事件.

See the live() method, it allows you to bind an event for all current, and future elements in the DOM that match the given selector.

 $(".s").live('click', function(){
    alert("Ok");

 });

jQuery文档说:

为现在和将来与当前选择器匹配的所有元素添加事件处理程序

Attach a handler to the event for all elements which match the current selector, now and in the future


注意,该答案写于2011年10月,当时jQuery 1.6.4为王.在1.7中不推荐使用live(),而推荐使用 on() .现在的等效语法是;


Note that this answer was written in October 2011, when jQuery 1.6.4 was king. live() was deprecated in 1.7 in favour of using on(). The equivalent syntax is now;

 $(document).on("click", ".s", function(){
    alert("Ok");
 });

这篇关于jQuery中的表上的Click事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆