在动态创建的Click事件上

时间:2013-09-19 14:42:59

标签: javascript jquery html-table

我有下表,它是在开头使用onload函数动态创建的。

<div id="first">
<table class="joma" id="joma">
<tbody>
<tr>
   <th>Id</th>
   <th>V No</th>
   <th>Biboron</th>
   <th>Taka</th>
</tr>
<tr><td class="rid">1</td><td>sss</td><td>222</td><td class="cv">4</td></tr>
<tr><td class="rid">2</td><td>xxx</td><td>2333</td><td class="cv">4</td></tr>
</tbody>
</table>
</div>

现在我需要能够点击应该给出相应值的<td class="rid">。在这种情况下为1或2.

我该怎么做?

我使用了以下方法:

$(document).ready(function() {
    $('.rid').click(function() {
        alert(this);
    });
});



$('.rid').click(function() {
    alert(this);
});

我没有得到任何东西。

3 个答案:

答案 0 :(得分:5)

使用.on()

$(document).on('click','.rid',function() {
     alert("this");
});

创建页面加载DOM时.rid不是页面的一部分。

因此您无法直接访问它们,您必须使用event delegation

答案 1 :(得分:3)

使用事件委托:

$(document).on('click', '.rid', function() {
    alert("this");
});
页面加载时不存在

.rid,因此将其绑定到存在的元素(通常是附加内容的容器,但由于我没有看到,document是一个安全的赌注。)

答案 2 :(得分:1)

$(document).ready(function() {
    $('.rid').click(function() {
        alert($(this).html());
    });
});

小提琴:http://jsfiddle.net/yraQS/

相关问题