【问题标题】:How do I make javascript change the element of specific element in rails如何让javascript更改rails中特定元素的元素
【发布时间】:2020-12-26 01:53:19
【问题描述】:

我的 rails 应用程序的 id 名称有点问题,我希望 javascript 通过按下按钮来禁用/启用字段。 我有一个很大的索引页面,人们可以在索引页面本身上对一堆图片进行评分。为此,我使用@posts.each do |post| 方法。 然后,用户应该能够使用滑块对图片进行评分,并且在使用滑块后,应该禁用范围。如果用户想要更改评级,可以单击“更改”,再次启用滑块。 我现在遇到的问题是启用功能。我在索引页面上有一堆帖子,所有的滑块和按钮都有相同的类名和 id。我试图为每个滑块和按钮指定一个带有id:'ratingPost#{post.id}' 的特定 ID,但问题是我无法让 javascript 知道刚刚单击的 postid 是什么。 你能帮我吗? 非常感谢你! 我的代码在这里:

#posts_index.html.erb

<% @posts.each do |post| %> 
  ...
    <% if post.ratings.find_by(user_id: current_user.id) %>
      <%= form_for [post, post.ratings.find_by(user_id: current_user.id)]  do |f| %>
        <%= f.range_field :score, class:"form-control-range slider", id:"ratingPost", onMouseUp:"submit()", onTouchEnd:"submit()", :disabled => true, data: { source: post} %>
      <% end %>
    <% else %>
      <%= form_for [post, @rating]  do |f| %>
        <%= f.range_field :score, class:"form-control-range slider", id:"formControlRange", onMouseUp:"submit()", onTouchEnd:"submit()"%>
      <% end %>
    <% end %>
  ...
        <% if post.ratings.find_by(user_id: current_user.id) %>
          <h2><%= post.ratings.where(user_id: current_user.id).last.score %>%</h2>
          <button id="RatingChangeButton"><p>CHANGE</p></button>
        <% end %>
      </div>
    </div>
  </div>
<% end %>

<script>
  document.getElementById("RatingChangeButton").addEventListener("click", enableRating);
  function enableRating() {
    document.getElementById("ratingPost").disabled=false;
  }
</script>

【问题讨论】:

    标签: javascript html ruby-on-rails


    【解决方案1】:

    理想情况下,您的 HTML 中不应有多个具有相同 ID 的元素,而应使用 class

    现在对于您的问题,您可以做的是将帖子的 ID 存储在 data attribute 中以用于您的按钮和评级字段,并在 javascript 函数中访问该 ID 以识别相应的滑块。类似的,

    https://codepen.io/anujmiddha/pen/NWRwwLL

    <p>Post 1: <input class="ratingPost" data-post-id="1" disabled></p>
    <p>Post 2: <input class="ratingPost" data-post-id="2" disabled></p>
    
    <p>
      <button class="RatingChangeButton" data-post-id="1" onClick="enableRating(this)">
        <p>CHANGE 1</p></button>
    </p>
    
    <p>
      <button class="RatingChangeButton" data-post-id="2" onClick="enableRating(this)">
        <p>CHANGE 2</p></button>
    </p>
    
    function enableRating(view) {
      let element = document.querySelector('[data-post-id="' + view.dataset.postId + '"],[class="RatingChangeButton"]');
      element.disabled = false;
      element.value = "enabled";
    }
    

    【讨论】:

    • 不知何故奏效了!我仍然必须使用特定的 post.id 对实际的 data-post-id 进行字符串插值,因为它们不是由实际代码分配的,而是由 for.each 分配的^^
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-14
    • 1970-01-01
    • 2018-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多