简体   繁体   English

动态添加可点击的行到表

[英]dynamically add clickable row to table

I'm trying to add rows to a table in HTML using JavaScript that are clickable. 我正在尝试使用可点击的JavaScript在HTML中向表中添加行。

Here is my codes: 这是我的代码:

HTML: HTML:

<table border="1" id="example" style="cursor: pointer;">
    <tr>
        <th>1</th>
        <th>2</th>
        <th>3</th>
        <th>4</th>
    </tr>
</table>

JavaScript: JavaScript的:

//clicked function
$('#example').find('tr').click( function(){
    alert('You clicked row '+ ($(this).index()) );
});

//add new row
var x=document.getElementById('example');
var new_row = x.rows[0].cloneNode(true);                      
new_row.cells[0].innerHTML = "hello";
x.appendChild( new_row );

The problem is that the newly added rows are clickable but won't go through the clicked function to get the alert. 问题是新添加的行是可点击的,但不会通过单击的功能来获取警报。

Anyone know why? 谁知道为什么?

The problem is that the newly added rows are clickable but won't go through the clicked function to get the alert. 问题是新添加的行是可点击的,但不会通过单击的功能来获取警报。

Anyone know why? 谁知道为什么?

When you are executing the initial binding of the click event to your tr elements the event is only bound to the tr elements which exist at that time in the DOM. 当您执行click事件与tr元素的初始绑定时,事件仅绑定到DOM中当时存在的tr元素。

That is how event binding works by default. 这就是事件绑定默认情况下的工作方式。 You can only bind what is currently in the DOM. 您只能绑定DOM中当前的内容。

However, using jQuery 1.7+'s on() or jQuery 1.6-'s delegate() methods you can bind event with delegation. 但是,使用jQuery 1.7 +的on()或jQuery 1.6- delegate()方法,您可以将事件与委托绑定。

This allows you to bind the event to the closest static parent element of the element you actual want to delegate the event to. 这允许您将事件绑定到您实际要委派事件的元素的最近的静态父元素。

I'm assuming the table itself is the closest static parent element, meaning it always exists and all you add dynamically is the tr elements. 我假设表本身是最接近的静态父元素,这意味着它总是存在,动态添加的是tr元素。

Using on() when using jQuery 1.7+ would look similar to this: 使用jQuery 1.7+时使用on()看起来与此类似:

$('#example').on('click', 'tr', function(){
    alert('You clicked row '+ ($(this).index()) );
});

Using delegate() when using jQuery 1.6- would look similar to this: 在使用jQuery 1.6时使用delegate()看起来类似于:

$('#example').delegate('tr', 'click' , function(){
    alert('You clicked row '+ ($(this).index()) );
});

What this will do is bind the event to the element with id of example but delegate the click to any tr clicked within that element. 这将做什么是将事件绑定到id为example的元素,但将click单击委托给该元素中单击的任何tr As the event is delegated each time, any newly added tr elements within #example will also be included. 由于事件每次都被委托,所以#example任何新添加的tr元素也将被包含在内。

Try this: Following code will take care of dynamically added rows. 试试这个:下面的代码将处理动态添加的行。

//clicked function
$('#example').on('click', 'tr', function(){
    alert('You clicked row '+ ($(this).index()) );
});

You are binding your click event on document.ready. 您正在对document.ready上的click事件进行绑定。 New elements added after wards wil not share this binding. 在病房之后添加的新元素将不会共享此绑定。

Yu can acheive what you are after by using .on() Yu可以通过使用.on().on()你的.on()

$("body").on("click", "#example tr", function(event){
  alert('You clicked row '+ ($(this).index()) );
});

DEMO DEMO

is this what you are trying to achieve? 这是你想要实现的目标吗?

<table border="1" id="example" style="cursor: pointer;">
    <thead>
        <tr>
            <th>1</th>
            <th>2</th>
            <th>3</th>
            <th>4</th>
        </tr>
    </thead>
    <tbody id="addHere"></tbody>
</table>

var addHere = document.getElementById("addHere");
var newTr;
var newTd;

function clicked(evt) {
    alert("clicked tr: " + evt.target.parentNode.id);
}

for (var i = 1; i < 11; i += 1) {
    newTr = document.createElement("tr");
    newTr.id = "row" + i;
    newTr.addEventListener("click", clicked, false);

    for (j = 1; j < 5; j += 1) {
        newTd = document.createElement("td");
        newTd.textContent = j;
        newTr.appendChild(newTd);
    }

    addHere.appendChild(newTr);
}

on jsfiddle jsfiddle

In your code it seems that you are looking for rows and then bind an event to any that you find. 在您的代码中,您似乎正在寻找行,然后将事件绑定到您找到的任何行。

You then proceed to add rows using Node.cloneNode 然后,继续使用Node.cloneNode添加行

Cloning a node copies all of its attributes and their values, including intrinsic (in–line) listeners. 克隆节点会复制其所有属性及其值,包括内部(内联)侦听器。 It does not copy event listeners added using addEventListener() or those assigned to element properties (eg node.onclick = fn). 它不会复制使用addEventListener()添加的事件侦听器或分配给元素属性的事件侦听器(例如node.onclick = fn)。

so there are no event handlers bound to any of these newly added elements. 所以没有事件处理程序绑定到任何这些新添加的元素。

Another way to deal with this would be to use jquery delegate event handler method (on) 另一种处理方法是使用jquery委托事件处理程序方法(on)

When a selector is provided, the event handler is referred to as delegated. 提供选择器时,事件处理程序称为委托。 The handler is not called when the event occurs directly on the bound element, but only for descendants (inner elements) that match the selector. 当事件直接发生在绑定元素上时,不会调用处理程序,但仅适用于与选择器匹配的后代(内部元素)。 jQuery bubbles the event from the event target up to the element where the handler is attached (ie, innermost to outermost element) and runs the handler for any elements along that path matching the selector. jQuery将事件从事件目标起泡到附加处理程序的元素(即最里面到最外层的元素),并为匹配选择器的路径上的任何元素运行处理程序。

and do the following. 并执行以下操作。

var addHere = document.getElementById("addHere");
var newTr;
var newTd;

function clicked(evt) {
    alert("clicked tr: " + evt.target.parentNode.id);
}

$(document).on("click", "#addHere tr", clicked);

for (var i = 1; i < 11; i += 1) {
    newTr = document.createElement("tr");
    newTr.id = "row" + i;

    for (j = 1; j < 5; j += 1) {
        newTd = document.createElement("td");
        newTd.textContent = j;
        newTr.appendChild(newTd);
    }

    addHere.appendChild(newTr);
}

on jsfiddle jsfiddle

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

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