【问题标题】:Check if certain word already has span as a wrapper检查某个单词是否已经有 span 作为包装器
【发布时间】:2019-11-10 14:42:33
【问题描述】:

我有多个 div 元素,它们在一些文本旁边包含一个电子邮件地址,例如 +example@email.com。现在我正在尝试添加 span 作为每个电子邮件地址的包装器。我找到了用一些跨度元素和文本替换以 + 开头的每个单词的解决方案。有没有办法可以检查 +example@email.com 是否已经有跨度​​?我不想多次包装它。我正在使用咖啡脚本

wrapAllThreadEmails = ->
  $('.comment-body-area').each (comment) ->
    text = $(this).html().replace(/\s\+(.*?)(\s|$)/g, '<span> +$1</span>$2')
    $(this).html(text)
    return

【问题讨论】:

    标签: javascript jquery coffeescript


    【解决方案1】:

    当然,您可以先检查返回的 HTML 是否与 &lt;span&gt; 匹配:

    wrapAllThreadEmails = ->
      $('.comment-body-area').each (comment) ->
        if not $(this).html().match(/<span>/) # Check for matching <span> here
          text = $(this).html().replace(/\s\+(.*?)(\s|$)/g, '<span> +$1</span>$2')
          $(this).html(text)
    

    你也可以从你的函数中删除return,一个表达式的CoffeeScript will always return the final value

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-04-17
      • 2020-07-01
      • 1970-01-01
      • 2020-07-06
      • 1970-01-01
      • 1970-01-01
      • 2017-09-25
      • 1970-01-01
      相关资源
      最近更新 更多