【问题标题】:How to access DOM element when using rails partial使用rails partial时如何访问DOM元素
【发布时间】:2021-10-07 21:55:34
【问题描述】:

我有一个内部带有 javascript 的 html,它使用 rails 部分。我无法从 rails partial 获取元素,而如果我在不使用 rails partial 的情况下放置按钮,我就能让它工作。

<%= render 'common_component_a', text: 'hello world', elmid: 'grab-this'%>
<script>
  if (document.getElementById('grab-this')) {
    document.getElementById('grab-this').onclick = function() {
     ...
    };
  }
</script>

在我的common_component_a 中,我有一个包含一些 css 样式的部分

<section>
  <span> Part A </span>
  <button id=<%= elmid %>><%= text %></button>
</section>

【问题讨论】:

  • 您真的应该考虑使用类而不是 id 并将此代码放在资产管道中的 JS 文件中。这看起来很像一个自己造成的问题。

标签: javascript ruby-on-rails


【解决方案1】:

你不会错过 id 标签周围的引号吗?

<button id="<%= elmid %>"><%= text %></button>

【讨论】:

  • 不带引号的属性值语法在 HTML5 中完全有效。我怀疑作者使用的是 XHTML。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-09-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-18
  • 2019-04-10
相关资源
最近更新 更多