Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/70.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Html 我可以在多个服务器上使用重复ID吗<;模板>;碎片?_Html_Dom_Xhtml_W3c Validation - Fatal编程技术网

Html 我可以在多个服务器上使用重复ID吗<;模板>;碎片?

Html 我可以在多个服务器上使用重复ID吗<;模板>;碎片?,html,dom,xhtml,w3c-validation,Html,Dom,Xhtml,W3c Validation,为什么HTML5验证在有重复的元素ID但在不同的上失败。我计划一次只使用一个模板,这样实际的DOM ID就不会被复制 比如: <template id="companyAccount"> <li><label>Company: <input type="text" id="account_name"></label></li> <li><

为什么HTML5验证在有重复的元素ID但在不同的
上失败。我计划一次只使用一个模板,这样实际的DOM ID就不会被复制

比如:

<template id="companyAccount">
   <li><label>Company: <input type="text" id="account_name"></label></li>
   <li><label>Street: <input id="account_street" ...
   ...
</template>
<template id="residentialAccount">
   <li><label>Name: <input type="text" id="account_name"></label></li>
   <li><label>Street: <input id="account_street" ...
   ...
</template>
<script>
...
let template = $(isResidential ? '#residentialAccount' : '#companyAccount').get(0).content;
$('#account_info').empty().append(template.cloneNode(true));
</script>

  • 公司:

  • 街道:正如TJBlackman提到的,
    id
    的每个
    值必须是唯一的。但是,在使用代码时,由您确定要导入的代码是否包含重复的
    id
    。此外,我已经基本停止使用验证器,因为它们没有得到很好的维护(而且W3C的CSS验证器非常糟糕),控制台、正确的错误处理和使用HTML5的XML解析器将告诉您几乎所有您需要知道的事情

    你有两个选择。您可以使用
    data account=“residential”
    (不要错误地使用camelcasting,因为这最终会使您与标准机构直接冲突)并通过
    文档检测属性。querySelectorAll

    function $(o)
    {
     var a = true;
    
     try {document.querySelectorAll(o);}
     catch(err) {a = false; console.log('Error: "'+o+'" is not a valid CSS selector.'); sound.notice();}
    
     return (a && document.querySelectorAll && document.querySelectorAll(o)) ? document.querySelectorAll(o) : false;
    }
    
    用法:
    $('[data account=“residential”]')[0]。长度
    $('[data account=“residential”]')[0]。值

    或者,你也可以像我一样使用我的平台,它将所有东西紧密集成在一起,尽管这是我使用的功能,你可能会出于特定目的决定瘦身。您可以使用
    document.createTreeWalker
    并逐字遍历每个元素以扫描
    walker.currentNode.hasAttribute('id')
    来测试
    document.getElementById
    。在将XML导入到我的平台上的DOM之前使用以下代码:

    /******** part of larger ajax() function ********/
    
    if (xhr.readyState == 4 && xhr.status != 204)
    {}
    
    //This code occurs within the above condition.
    var r = jax_id_duplication_prevention(xhr.responseXML,param_id_container_pos,id_container);
    
    if (r)
    {
     if (param_id_container_pos=='after') {id_container.parentNode.insertBefore(xml.getElementsByTagName('*')[0],id_container.nextSibling);}
     else if (param_id_container_pos=='before') {id_container.parentNode.insertBefore(document.importNode(xml.getElementsByTagName('*')[0],true),id_container);}
     else if (param_id_container_pos=='first')
     {
      if (id_container.childNodes.length > 0) {id_container.insertBefore(document.importNode(xml.getElementsByTagName('*')[0],true),id_container.firstChild);}
      else {id_container.appendChild(document.importNode(xml.getElementsByTagName('*')[0],true));}
     }
     else if (param_id_container_pos=='inside') {id_container.appendChild(document.importNode(xml.getElementsByTagName('*')[0],true));}
     else if (param_id_container_pos=='replace') {id_container.parentNode.replaceChild(document.importNode(xml.getElementsByTagName('*')[0],true),id_container);}
     else if (param_id_container_pos=='fragment')
     {
      if (option.fragment) {delete option.fragment;}
      option.fragment = document.importNode(new DOMParser().parseFromString(xhr.responseText,'application/xml').childNodes[0],true);
      if (id_container && typeof id_container == 'function') {id_container();}
     }
     else {alert('Error: unknown position to import data to: '+id_container_pos);}
    }
    /******** part of larger ajax() function ********/
    
    function ajax_id_duplication_prevention(xml,param_id_container_pos,id_container)
    {
     var re = true;
     if (typeof id_container == 'string' && id_container.length > 0 && id_(id_container)) {id_container = id_(id_container);}
    
     if (typeof option.id_fade == 'string' && option.id_fade.length > 0 && id_(option.id_fade)) {element_del(option.id_fade); option.id_fade = '';}
    
     if (typeof xml.firstChild.hasAttribute == 'function')
     {
      if (xml.firstChild.hasAttribute('id') && xml.firstChild.getAttribute('id').length > 0 && id_(xml.firstChild.getAttribute('id')) && id_(xml.firstChild.id).parentNode.id=='liquid') {change(xml.firstChild.id,'fade');}
    
      if (xml.firstChild.hasAttribute('id') && xml.firstChild.getAttribute('id').length > 0 && id_(xml.firstChild.id) && !id_(xml.firstChild.id).parentNode.id=='liquid') {re = false;}
      else if (typeof document.createTreeWalker=='function')
      {
       var idz = [];
       try
       {
        var walker = document.createTreeWalker(xml,NodeFilter.SHOW_ELEMENT,null,false);
    
        while (walker.nextNode())
        {
         if (walker.currentNode.hasAttribute('id') && walker.currentNode.getAttribute('id').length > 0)
         {
          if (walker.currentNode.id==undefined && walker.currentNode.nodeName.toLowerCase()=='parsererror') {console.log('Error: a parser error was detected.');}
          else if (walker.currentNode.id==undefined) {alert('walker.currentNode.nodeName = '+walker.currentNode.nodeName+'\n\n'+document.serializeToString(xml));}
          else
          {
           for (var i = 0; i<id_('liquid').childNodes.length; i++)
           {
            if (id_('liquid').childNodes[i].nodeType==1 && id_(walker.currentNode.id) && is_node_parent(walker.currentNode.id,id_('liquid').childNodes[i]) && (param_id_container_pos!='replace' || walker.currentNode.id!=id_container.id))
            {
             if (param_id_container_pos != 'replace' && id_container != walker.currentNode.id) {element_del(id_('liquid').childNodes[i]);}//If changing operator test: ajax('get','?ajax=1&web3_url=/'+url_section()+'/'+url_page(),'replace',push_current_id());
            }
           }
    
           var n = id_(walker.currentNode.id);
           if (in_array(walker.currentNode.id,idz))
           {
            var fd = new FormData();
            fd.append('ajax','error_xml');
            fd.append('post_error','Duplicate id <code>'+walker.currentNode.id+'</code>.');
            fd.append('post_url',url_window().split(url_base())[1].split('?')[0]);
            fd.append('post_xml',new XMLSerializer().serializeToString(xml));
            if (fd) {ajax('post',path+'/themes/',fd);}
    
            modal.alert('Error: can not import XML, the id \''+walker.currentNode.id+'\' was detected twice in the layer being imported. Duplicated ID\'s break expected functionality and are illegal. While the XML content was not imported it is still possible that the related request was successful. It is possible to override this problem by simply doing a full request (press the Go button in your browser\'s graphic user interface) however if the id is referenced programmatically the website may exhibit unusual behavior.');
            break;
            setTimeout(function()
            {
             history.back();
             push_reload();
             console.log('Developer: duplicate id '+walker.currentNode.id+' was encounterted.');
             if (status >= 9) {modal.xml('Duplicate ID Error', '%3Cp%3EError%3A%20the%20id%20%3Ccode%3E'+walker.currentNode.id+'%3C%2Fcode%3E%20occurred%20twice%20and%20therefore%20the%20page%20can%20not%20be%20viewed.%3C%2Fp%3E%3Cp%3EFor%20debugging%20and%20fixing%20purposes%20you%20should%20consider%20opening%20the%20URL%20in%20a%20new%20tab.%3C%2Fp%3E%3Cdiv%20class%3D%22center%20margin%22%3E%3Cinput%20onclick%3D%22modal.close()%3B%22%20tabindex%3D%223%22%20type%3D%22button%22%20value%3D%22Close%22%20%2F%3E%3C%2Fdiv%3E');}
             else {modal.xml('Duplicate ID Error', '%3Cp%3EError%3A%20the%20id%20%3Ccode%3E'+walker.currentNode.id+'%3C%2Fcode%3E%20occurred%20twice%20and%20therefore%20the%20page%20can%20not%20be%20viewed.%3C%2Fp%3E%3Cdiv%20class%3D%22center%20margin%22%3E%3Cinput%20onclick%3D%22modal.close()%3B%22%20tabindex%3D%223%22%20type%3D%22button%22%20value%3D%22Close%22%20%2F%3E%3C%2Fdiv%3E');}
             re = false;
            },4000);
           }
           else {idz.push(walker.currentNode.id);}
          }
    
          if (id_(walker.currentNode.id) && (param_id_container_pos!='replace' && walker.currentNode.id!=id_container.id && !is_node_parent(walker.currentNode.id,id_container)))
          {//ajax replace (carousel loader) complications if changed.
           re = false;
           modal.alert('Error: unable to import page, the id \''+walker.currentNode.id+'\' already exists in the DOM.');
           break;
          }
         }
        }
       }
       catch (err) {}//IE9
      }
     }
    
     return re;
    }
    

    无论您如何解决这个问题,它都不是由标准机构解决的,必须由开发人员明确处理。未能处理重复的
    id
    属性/值将导致在某个点选择错误的元素,随着时间的推移,这些元素可能会悄悄地累积多年来无人注意到的受损/格式错误的数据,因此如果不彻底破坏受其影响的任何业务关系,很容易受到阻碍。祝你好运

    发布示例代码。您如何“一次只显示一个?”@TJBlackman-我添加了一个示例。ID必须是全局唯一的,因此当它们存在时,只有一个。看起来同一个ID在HTML文件中可能出现多次,可能并不总是如此,但即使只是一秒钟,它也会失败。如果必须使用相同的ID,则必须100%确保在添加其他ID之前完全删除其中一个ID。但只要使用一个类或数据属性,问题就解决了。据我所知,每个模板的内容都放在一个单独的文档中,因此每个id在其文档中都是唯一的,不应该是验证错误。但坦率地说,唯一能回答这个问题的人是sideshowbarker,所以你也可以