我有一个包含很多节点的 Jstree,其中一些节点具有相同的 ID。
我想知道,我该如何做到这一点,以便如果有人选择
其中一个节点,它将选择具有相同 id 的每个节点。
我尝试与
onselect: function (node) {
但我不确定到底要做什么,
而且我不确定如何手动选择一个节点
(因为它都是用 selected: 属性完成的)
ID在文档中必须是唯一的,所以我假设您需要这样做,因为您从某个地方获取数据并需要对其进行清理。如果可以,请解决问题的根源。
但是,如果不能,您可以遍历树中的元素以查找匹配的 ID;像这样的东西:
var theTargetID = /* ...whatever ID you're looking for... */;
$(theTree).find("*").each(function(element) {
if (this.id == theTargetID) {
// it matches the ID
}
});
这将创建一个可能很大的临时数组(匹配树的所有后代元素)。这可能是你最好使用无聊的老式 DOM 遍历而不是 jQuery 的漂亮包装器的地方,因为你试图用无效的文档结构(多个 ID)做一些事情。
以下是寻找目标 ID 的原始 DOM 遍历可能的样子:
function traverse(theTargetID, element) {
var node;
if (element.id == theTargetID) {
// It matches, do something about it
}
// Process child nodes
for (node = element.firstChild; node; node = node.nextSibling) {
if (node.nodeType === 1) { // 1 == Element
traverse(theTargetID, node);
}
}
}
这假定element
参数实际上是一个 DOM 元素(不是 jQuery 对象或文本节点等)。它检查元素的id
,然后处理其子元素,如有必要,递归处理。这避免了创建一个潜在的大数组。
请注意,我指的是树节点,而不是其中的叶子。您希望在加载树时执行此操作一次,而不仅仅是在选择树中的节点时——因为您希望尽可能短地获得无效结构并主动修复它。
TJ Crowder已经说过,ID 在文档中必须是唯一的。我认为如果存在重复的 ID,您的 jsTree 中可能会出现非常奇怪的效果,因此我建议您执行以下操作。
对于您单击的每个节点,将 id 属性的值存储在var nodeId
下面的示例中。示例代码将为您找到重复项var nodeId
。如果发现重复项,则除了第一个找到的节点之外的所有节点都应将 id 更改为唯一 id。您可以通过将值i
或随机文本字符串附加到 id 来做到这一点。
这就是我现在能为你做的一切。如果您可以向我们提供一些更详细的信息(HTML 和您当前的 Javascript 代码)会有所帮助。
var nodeId = 'the-node-id'; // The id of your node id here.
$('#' + nodeId).each(function() {
var matchingIds = $('[id='+this.id+']'); // May find duplicate ids.
if (matchingIds.length > 1 && matchingIds[0] == this) {
// Duplicates found.
for (i = 0; i < matchingIds.length; i++) {
// Whatever you like to do with the duplicates goes here. I suggest you give them new unique ids.
}
}
});
更新:这是一种替代解决方案,在页面加载后直接找到重复的 id,类似于 TJ Crowder 的建议。
$('[id]').each(function() { // Selects all elements with ids in the document.
var matchingIds = $('[id='+this.id+']'); // May find duplicate ids.
if (matchingIds.length > 1 && matchingIds[0] == this) {
// Duplicates found.
for (i = 0; i < matchingIds.length; i++) {
// Whatever you like to do with the duplicates goes here. I suggest you give them new unique ids.
}
}
});