简体   繁体   English

点击事件 <td> 动态创建

[英]On Click event on <td> created dynamically

I have the following table which is created dynamically using a onload function at the beginning. 我有下表,它是在一开始使用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>

Now I need to be able to click the <td class="rid"> which should give the the corresponding value. 现在,我需要能够单击<td class="rid"> ,它应该提供相应的值。 in this case 1 or 2. 在这种情况下为1或2。

How do I do this? 我该怎么做呢?

I have used the following methods: 我使用以下方法:

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



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

I am not getting anything with this. 我对此一无所获。

Use .on() 使用.on()

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

when page loaded DOM is created .rid is not the part of the page. 创建页面加载的DOM时, .rid不是页面的一部分。

So you can not access them directly you have to use event delegation 因此,您不能直接访问它们,而必须使用event delegation

Use event delegation: 使用事件委托:

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

.rid doesn't exist on page load, so bind it to an element that does exist (usually the container to where your appending the content, but since I didn't see one, document is a safe bet). .rid在页面加载时不存在,因此将其绑定到确实存在的元素(通常是将内容附加到的容器,但是由于我没有看到,因此document是一个不错的选择)。

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM