如何让javascript更改rails中特定元素的元素
我的rails应用程序的id名称有点问题,我希望javascript通过按下按钮来禁用/启用字段。 我有一个很大的索引页面,人们可以在索引页面上给一堆图片打分。为此,我使用了如何让javascript更改rails中特定元素的元素,javascript,html,ruby-on-rails,Javascript,Html,Ruby On Rails,我的rails应用程序的id名称有点问题,我希望javascript通过按下按钮来禁用/启用字段。 我有一个很大的索引页面,人们可以在索引页面上给一堆图片打分。为此,我使用了@posts.each do | post |方法。 然后,用户应该能够使用滑块对图片进行评级,并且在使用滑块后,应该禁用该范围。如果用户想要更改评级,可以单击“更改”,再次启用滑块。 我现在的问题是启用函数。我在索引页面上有很多帖子,所有的滑块和按钮都有相同的类名和ID。我尝试给每个滑块和按钮一个特定的id,id为:'ra
@posts.each do | post |
方法。
然后,用户应该能够使用滑块对图片进行评级,并且在使用滑块后,应该禁用该范围。如果用户想要更改评级,可以单击“更改”,再次启用滑块。
我现在的问题是启用函数。我在索引页面上有很多帖子,所有的滑块和按钮都有相同的类名和ID。我尝试给每个滑块和按钮一个特定的id,id为:'ratingPost#{post.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>
...
true,数据:{source:post}%>
...
%
改变
document.getElementById(“评级更改按钮”)。addEventListener(“单击”,启用评级);
启用功能(){
document.getElementById(“ratingPost”).disabled=false;
}
理想情况下,HTML中不应该有多个ID相同的元素,而应该使用类
现在,对于您的问题,您可以做的是将帖子的id存储在按钮和评级字段的中,并在javascript函数中访问该id以识别相应的滑块。大概
第1篇:
职位2:
变化1
变化2
功能启用(视图){
let element=document.querySelector(“[data post id=“”+view.dataset.postId+”],[class=“RatingChangeButton”]”);
element.disabled=false;
element.value=“已启用”;
}
理想情况下,HTML中不应该有多个ID相同的元素,而应该使用类
现在,对于您的问题,您可以做的是将帖子的id存储在按钮和评级字段的中,并在javascript函数中访问该id以识别相应的滑块。大概
第1篇:
职位2:
变化1
变化2
功能启用(视图){
let element=document.querySelector(“[data post id=“”+view.dataset.postId+”],[class=“RatingChangeButton”]”);
element.disabled=false;
element.value=“已启用”;
}
这真管用!我仍然必须用特定的post.id对实际的数据post id进行字符串插值,因为它们不是由实际的代码指定的,而是由for.each^^^指定的,它以某种方式工作!我仍然必须用特定的post.id对实际的数据post id进行字符串插值,因为它们不是由实际代码指定的,而是由for.each指定的^^