【问题标题】:How to include an id (or class) in an ERB element如何在 ERB 元素中包含 id(或类)
【发布时间】:2017-06-20 09:03:47
【问题描述】:

我有这段代码用于在一篇文章上显示 cmets,该文章使用 ERB 元素从数据库中获取和显示信息:

<div class="comments">
  <h4 class="comment_author">Comment by <%= comment.author_name %></h4>
  <p class="comment"><%= comment.body %></p>
</div>

我想以不同的方式格式化 comment.author_name,所以我想在第二行添加一个 id,例如

<h4 class="comment_author">Comment by <%= comment.author_name, id: "commenter" %></h4>

但是,当我这样做时,我得到以下error message

我过去添加了类和 id 来形成具有 :class=> "name" 语法如下:

<%= f.submit 'Create Article', :class => 'create_new_article_button'%>

但这似乎也不起作用。是否有其他方法可以将 id 和类添加到非表单 ERB 元素?

提前致谢!

【问题讨论】:

  • &lt;h4 class="comment_author", id='commenter''&gt;Comment by &lt;%= comment.author_name %&gt;&lt;/h4&gt;
  • 您尝试将id 添加到错误的位置。您目前正尝试在 h4 的内容中添加 id 而不是标签本身。

标签: html css ruby-on-rails erb


【解决方案1】:

&lt;%= comment.author_name %&gt; 不是标签/元素,它只是一个值(我假设为字符串),因此您不能向其添加id 属性。你可以这样做

<h4 class="comment_author">Comment by 
   <span id="commenter"><%= comment.author_name %></span>
</h4>

或者将id="commenter" 直接提供给&lt;h4&gt; 标签并使用它来定位span

因为f.submit 指的是表单的提交按钮,所以它更早起作用,这意味着它实际上是一个 HTML 元素,因此您可以向其添加 idclass

【讨论】:

  • 我没有意识到它不是标签/元素,这很有意义!感谢您的帮助!
【解决方案2】:

您不能向内容添加 ID。相反,您应该将 ID 添加到包装您的内容的元素中。你的情况应该是这样的

<h4 class="comment_author" id='commenter'>Comment by <%= comment.author_name %></h4>

这将创建具有 ID 'commenter' 的 h4 元素。

【讨论】:

    【解决方案3】:

    你在这里混淆了

    我过去添加了类和 id 来形成具有 :class=> "name" 语法如下:

    'create_new_article_button'%> 但这似乎也不起作用。

    表单元素将接收class 具有它的参数之一。检查文档here。但是&lt;%= %&gt; 只会在视图中显示 ruby​​ 代码的最终结果,但不会向 DOM 添加任何 html 内容。请在实施某些内容之前仔细阅读文档。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-05-27
      • 2020-06-15
      • 2010-10-03
      • 1970-01-01
      • 2014-05-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多