Javascript jQuery DataTables:如何通过 tr 的行 id 获取行索引(或 nNode)?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7503306/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 02:32:21  来源:igfitidea点击:

jQuery DataTables: How to get row index (or nNode) by row id of tr?

javascriptjquerycssdomdatatables

提问by Mathias

I have a dataTables <table id="myTable">. I would like to fnUpdate()and fnDestroy()my rows. every row has an id, eg: <tr id="16">. To fnUpdate()/fnDestroy()the appropriate <tr>, I need to get that row's index. For this I try to use fnGetPosition(), but the way I try it is not the way to do it:

我有一个 dataTables <table id="myTable">。我想fnUpdate()fnDestroy()我的行。每行都有一个 id,例如:<tr id="16">。对于fnUpdate()/fnDestroy()适当的<tr>,我需要获取该行的索引。为此,我尝试使用fnGetPosition(),但我尝试的方式不是这样做的方式:

$("#myTable").fnGetPosition( $("#16") )

results in

结果是

TypeError: nNode.nodeName is undefined [Break On This Error] var sNodeName = nNode.nodeName.toUpperCase();

TypeError: nNode.nodeName 未定义 [Break On This Error] var sNodeName = nNode.nodeName.toUpperCase();

Which makes sense, as fnGetPosition()expexts nNode (in my case a HTMLTableRowElement).

这是有道理的,因为fnGetPosition()expexts nNode(在我的例子中是 HTMLTableRowElement)。

How do I get the HTMLTableRowElement that has id="16"?

如何获得具有 的 HTMLTableRowElement id="16"

EDIT: A correct answer to my question is: document.getElementById("16"). Based on that, I would like to change my question to:

编辑:正确的答案,我的问题是:document.getElementById("16")。基于此,我想将我的问题更改为:

Why does

为什么

$("#myTable").fnGetPosition( document.getElementById("16") ) 

work, but

工作,但是

$("#myTable").fnGetPosition( $("#16") )

fails?

失败?

回答by Michael Kopec

For anyone who still has this problem, try this:

对于仍然有此问题的任何人,请尝试以下操作:

$("#myTable").fnGetPosition( $("#16")[0] )

To get the same result as document.getElementByIdyou should access the first element in the jQuery object.

要获得与document.getElementById您应该访问 jQuery 对象中的第一个元素相同的结果。

回答by Ashkan Aryan

document.getElementById() returns a DOM object, and everything on the DOM object will be inherently accessible.

document.getElementById() 返回一个 DOM 对象,并且 DOM 对象上的所有内容都将是可访问的。

JQuery's $('#...') returns a wrapper around a single DOM object OR a set of DOM objects (depending on the selector) and as such, it does not return the actual DOM Object. It makes it easier to work with DOM objects.

JQuery 的 $('#...') 返回围绕单个 DOM 对象或一组 DOM 对象(取决于选择器)的包装器,因此,它不会返回实际的 DOM 对象。它可以更轻松地处理 DOM 对象。

The reason you are getting that error in the second case would be that $(#...) is not actually a DOM object.

在第二种情况下出现该错误的原因是 $(#...) 实际上不是 DOM 对象。

回答by Nicola Peluchetti

You sould do:

你应该这样做:

var oTable = $('#myTable').dataTable();
oTable.fnGetPosition( $("#myTable #16") );