简体   繁体   English

Rails 3将变量从link_to传递给javascript

[英]Rails 3 Passing a variable from link_to to javascript

If a user is on a form page, I am trying to throw a confirm message if they navigate away without clicking the update button. 如果用户在表单页面上,如果他们离开而未单击“更新”按钮,我将尝试抛出一条确认消息。

The coffeescript code I am using is as follows 我正在使用的coffeescript代码如下

# used to detect if a user is navigating off a page
if form_click == true
  window.onbeforeunload = ->
    "You have unsaved data! do you really want to exit?"

If I use if 1 ==1 or 1 ==2 as a test case, it works perfectly fine. 如果我使用1 == 1或1 == 2作为测试用例,则可以很好地工作。 However, I am having diffculty in sending a variable from the link_to code to set form_click. 但是,我很难从link_to代码发送变量来设置form_click。

I have tried the following 我尝试了以下

<%= f.button :button, :class => 'btn-primary',
            data: {form_click: true},
            remote: true %>

But I am not able to pass the variable to the coffeescript code. 但是我无法将变量传递给coffeescript代码。 I am definitely not proficient with javascript and coffeescript, as this probably shows, and would be grateful of any advice on how to resolve this would be much appreciated 我肯定不精通javascript和coffeescript,正如这可能显示的那样,并感谢任何有关如何解决此问题的建议

Have a look at the generated HTML. 看一下生成的HTML。 I suspect that the link_to is creating something similar to: 我怀疑link_to正在创建类似于以下内容的内容:

<button class="btn-primary" data-form_click="true" data-remote="true"></button>

If so then the coffeescript you need to have would be something like: 如果是这样,那么您需要的咖啡脚本将是这样的:

$('data-form_click').click( ->
  if $(this).attr('data-form_click') == 'true'
    window.onbeforeunload = ->
      confirm("You have unsaved data! Do you really want to exit?")
)

The code above is off the cuff, but the main point is that the attribute on the button is a string, not a boolean, so you need to adjust accordingly. 上面的代码是袖手旁观,但是要点是按钮上的属性是字符串,而不是布尔值,因此您需要进行相应的调整。

Use the JS debugging tools to place a breakpoint so you can inspect the value of form_click is also another way to see what you should be comparing to. 使用JS调试工具放置一个断点,以便您可以检查form_click的值, form_click也是查看与之比较的另一种方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM