【问题标题】:Rails - Removing 'data-confirm' attributeRails - 删除“数据确认”属性
【发布时间】:2017-10-24 18:40:32
【问题描述】:

Rails 使用不显眼的 javascript 在(提交)按钮上提示确认消息。这些消息存储在按钮/链接的data-confirm 属性中。

现在,假设您有时只想确认,例如我只想在忙于编辑价格时提示,您显然使用 javascript (jQuery) 添加和删除这些属性

$('.create-order').attr('data-confirm', "Warning: You are busy editing item prices and you haven't applied your changes yet. Continue?");

$('.create-order').removeAttr('data-confirm');

这是有效的,属性肯定被追加和删除(我仔细检查了)。但我注意到,一旦消息显示一次,之后每次都会显示,即使在属性被删除后也是如此。 (我也邀请任何人试试这个并分享你的结果?)

我怎样才能阻止这种情况发生?

【问题讨论】:

  • 在这种情况下,我宁愿自己实现确认消息,并在我想要的时候准确显示它们。正如您所发现的那样,在不查看实现的情况下覆盖这样的 javascript Rails 使用可能会出现问题,并且实现可能会在未来的版本中发生变化并再次弄乱您的应用程序。

标签: javascript jquery ruby-on-rails dialog custom-data-attribute


【解决方案1】:

在您的情况下,我将覆盖 jquery_ujs.js 文件中的 confirm 方法,如下所示:

$.rails.confirm  = function(message){
 //your logic here : must return true or false, you can call js default confirm method
}

【讨论】:

【解决方案2】:

这就是我的处理方式(似乎更简单):

导轨形式:

<%= @form_for(@obj) do |f| %>
    <%= f.text_field :attribute %><br />
    <%= f.radio_button :my_radio, false %> Finished <%= f.radio_button :my_radio, true %> Not yet !<br />
    <%= f.submit id: "submit" %>
<% end %>

还有 Jquery:

<script>
    $("#submit").click(function() {
        if ($("#my_radio_false").is(':checked')) {
            return confirm("Are-you sure ?");
            return true;
        }
    });
</script>

你可以在这里测试它:

$("#submit").click(function() {
  if ($("#my_radio_false").is(':checked')) {
    return confirm("Are you sure ?");
    return true;
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
  <input type="text" /><br />
  <input value="true" name="analysis[is_analysed]" id="my_radio_true" type="radio"> Finished 
  <input value="false" name="analysis[is_analysed]" id="my_radio_false" type="radio" checked="checked"> Not Yet !<br />
  <input name="commit" value="Test it !" id="submit" type="submit">
</form>

希望有帮助

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多