首页 > 解决方案 > 如果 DOM 中的元素有重复的 ID 并且我查询创建的第二个元素会发生什么

问题描述

我正在使用 js 代码创建 html 元素,接下来我应该查询这些元素以将它们与一些 svg 行插件连接起来。问题是,一个在原始元素内部,另一个不在。

这些重复的ID会发生什么?jquery 是否能够找到第二个?

function paintIds(table){
    $.post('findIds', { 
        chain : table // this is the parameter
    }, function(response) {
        var vec = response.split(","); // the response is a comma separated list of table fields, so i turn it into an array
        vec.forEach(function(c){
            // paint fields on screen
            $('#'+'DW'+table).append('<span class="key" id="sn'+c+'">'+c+'</span>');
        });
        $('#'+'DW'+table).append('<hr>'); put an ht in the end of the list
    });
}

所以会发生这种情况

运行结果

我可以有 2 个称为 ID_GAL 的元素。然后我去尝试将这些元素与另一个函数连接起来,但有时元素 ID 会重复,因为它们是某些表中的字段名称。ID 格式类似于 #snFIELD_ID

target = $('#sn'+elem).eq(0); 
                                if($('#sn'+elem,'#'+c.replace(/\./g, '')).length == 1) {
                                    console.log('target inside origin')
                                    target= $('#sn'+elem).eq(1); // if i find that one is inside another, then i change my target var to the second
                                }else{
                                    console.log('target is not inside origin')
                                }
                                console.log(target.id + '==> #sn' + elem);
                                var connex = jQuery('#'+c.replace(/\./g, '')).connections({ to: target,'class': 'lineas' });
                                setInterval(function() {
                                      connex.connections('update');
                                    }, 200);

所以,事情是,因为它们有时是重复的,所以我无法画线,因为元素在原点内。在示例中 DW.DIM GAL > ID_GAL 应该与 DW.DIM_ART > ID_GAL 连接

如何找到我的第二个 id 进行连接?

标签: javascripthtml

解决方案


推荐阅读