HTML注释(如果没有javascript)



我知道无论浏览器是否为IE,甚至是IE版本,我都可以显示/隐藏内容。我想知道是否也可以使用其他表达式,如

<!--[if 1 == 0]-->
This should be hidden
<!--[endif]-->

这背后的原因是,我正在发送自动生成的电子邮件,对我来说,在模板电子邮件中插入这样的评论会更容易,而不是创建多个模板。

如果你有一个模板系统,那么在你的模板中创建它。无论如何,当您呈现模板时,您会计算条件,但不是打印"0==1"或"0==0",而是使用模板的打印或不打印以下段落

我知道这看起来像是一个很长的答案,但我只是想把代码分成几个小函数,每个函数都有自己的工作-有点-,首先用querySelectorAll选择数组中类名为hasComment的每个元素,然后把这个数组传递给updateHTML()函数,遍历它的元素,并为数组中的每个项调用returnComment()函数。

returnComment()函数首先对传递给它的元素调用hasComment()函数,并使用.replace()来获得确切的字符串。函数hasComment()循环通过元素的child nodes,如果子节点的nodeType8,则它是一个注释,我们返回注释<!---->之间的文本。

.replace(/[|]/ig, '');省略括号以获得showhide的值,根据该值,我们"隐藏"或"显示"子.contentDiv分区。

JS Fiddle

var commentDivs = document.querySelectorAll('.hasComment');
updateHTML(commentDivs);
function updateHTML(arr) {
  for (var i = 0; i < arr.length; i++) {
    var childDiv = arr[i].querySelector('.contentDiv'),
      showIt = returnComment(arr[i]);
    if (showIt == 'show') {
      childDiv.style.display = 'block';
      console.log('Div-' + (i + 1) + ': shown');
    } else if (showIt == 'hide') {
      childDiv.style.display = 'none';
      console.log('Div-' + (i + 1) + ': hidden');
    }
  }
}
function returnComment(element) {
  var comment = hasComment(element);
  comment = comment.replace(/[|]/ig, '');
  return comment;
}
function hasComment(element) {
  for (var i = 0; i < element.childNodes.length; i++) {
    if (element.childNodes[i].nodeType == 8) {
      return element.childNodes[i].data;
    }
  }
}
<div class="hasComment">
  <!--[hide]-->
  <div class="contentDiv">Div -1: This should be hidden</div>
</div>
<hr>
<div class="hasComment">
  <!--[hide]-->
  <div class="contentDiv">Div -2: Again, This should be hidden</div>
</div>
<hr>
<div class="hasComment">
  <!--[show]-->
  <div class="contentDiv">Div -3: But this should be shown</div>
</div>

----------

注意:

  • 对每个.hasComment元素的所有内容进行封装,使内容控制更容易
  • 上述解决方案仅适用于.hasComment元素子级的最高级,因此,如果您在.contentDiv中有其他注释,则这些注释不会受到影响
    演示小提琴
  • 您可能会使用[if 1==0]进行"模板化",就像在代码中一样,然后使用eval()或更复杂的正则表达式来检查它,但IMHO我认为使用showhide看起来更容易,而且大多数错误都更少,因为您在文档中一遍又一遍地这样做
  • 关于nodeType的更多详细信息:
    • https://developer.mozilla.org/en-US/docs/Web/API/Node/nodeType
    • https://developer.mozilla.org/fr/docs/Web/API/Node/nodeType
    • http://www.w3schools.com/xml/dom_nodetype.asp

由于您是为电子邮件客户端开发的,所以这是不可能的。你需要弄清楚如何针对不同的客户。然后通过CSS将display属性设置为受影响的属性。

理想情况下,您的电子邮件不需要任何类似的疯狂逻辑。你的电子邮件有臭味。更不用说,你在电子邮件中输入的任何内容都是可以查看的,所有人需要做的就是关闭HTML呈现或查看源代码。

相关内容

最新更新