我正在尝试使用按钮与Rails4异步切换文本和类。当页面刚刚重新呈现时,我的代码运行良好,但我希望能够异步切换UI。目前,我需要双击我的按钮才能使其正常工作。
我想我遇到的问题是页面上有多个button_to元素,因为我想列出它们的列表。我正在尝试定位目标元素,但我不知道如何从ajax XMLHttpRequest中获取它。
_interested_button.html.erb
<% if interested? locals[:question] %>
<%= button_to "Interested", toggle_interest_path, remote: true, params: {question: locals[:question][:id]}, class: 'btn btn-success interested_button' %>
<% else %>
<%= button_to "Show Interest", toggle_interest_path, remote: true, params: {question: locals[:question][:id]}, class: 'btn btn-default interested_button', id: 'interested_button' %>
<% end %>
interest_box.js.erb
$(function(){
$('.interested_button').mousedown(function() {
var newVal = ($(this).val() === "Interested") ? "Show Interest" : "Interested";
$(this).val(newVal);
$(this).toggleClass('btn-default btn-success');
});
});
question_interest_controller.rb
class QuestionInterestController < ApplicationController
# handle the show interest button
def interest_box
@question_interest = QuestionInterest.find_by(expert: current_user.id, question: params[:question])
# Toggle between creating a new question interest and destroying the interest
if @question_interest
@question_interest.destroy
else
@question_interest = QuestionInterest.new(expert: current_user.id, question: params[:question])
@question_interest.save
end
respond_to do |format|
format.js
end
end
end
views/question/index.html.erb
<div class="container">
<div class="page-header"><h1>Listing Questions</h1></div>
<% @questions.each do |question| %>
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title"><%= link_to question.title, question %></h3>
<% if expert? %>
<!-- Toggle between interested and not interested with ajax :) -->
<%= render 'interested_button', locals: {question: question} %>
<% end %>
</div>
<div class="panel-body question-body">
<%= question.body.html_safe %>
</div>
</div>
<% end %>
</div>
不,在这种情况下不需要mousedown回调,click
是链接激活的默认事件。只需将内容直接放在js.erb
文件中
var $button = $('.interested_button')
var newVal = ($button.val() === "Interested") ? "Show Interest" : "Interested";
$button.val(newVal);
$button.toggleClass('btn-default btn-success');
祝你好运。
这样做:
#app/views/interests/interest_box.js.erb
$(document).on("click", ".interested_button", function() {
var newVal = ($(this).val() === "Interested") ? "Show Interest" : "Interested";
$(this).val(newVal);
$(this).toggleClass('btn-default btn-success');
});
--
老实说,这是对format.js
的不当使用(它旨在让您能够调用基于请求的功能);你最好将以上内容放入你的资产管道中:
#app/assets/javascripts/application.js
$(document).on("click", ".interested_button", function() {
var newVal = ($(this).val() === "Interested") ? "Show Interest" : "Interested";
$(this).val(newVal);
$(this).toggleClass('btn-default btn-success');
});