简体   繁体   English

使用jQuery / Coffeescript在页面加载上触发函数

[英]Firing a function on page load using jQuery/Coffeescript

I have a form that shows or hide elements based on the selections they user makes. 我有一个表单,根据用户的选择显示或隐藏元素。 When the form fails validation I need these elements to show or hide on page load based on their previous selections. 当表单验证失败时,我需要根据以前的选择在页面加载时显示或隐藏这些元素。

My code looks a little like this: 我的代码看起来有点像这样:

ready = ->
  $(".radio-button").on "ready change", ->
    value = $(this).val()
    if value != true
        $("#some-element").show();
    else
        $("#some-element").hide();

$(document).ready(ready)
$(document).on('page:load', ready)

The change handler works fine but the ready handler never fires. 更改处理程序工作正常,但就绪处理程序永远不会触发。 I'm guessing this has something to do with the ready action finishing before the jquery can bind its own handler? 我猜这与jquery绑定自己的处理程序之前的准备动作完成有关吗?

What is the purpose for attaching the "ready" event to the .radio-button selector? 将“ready”事件附加到.radio按钮选择器的目的是什么? I'm not quite sure if that is valid. 我不太确定这是否有效。 Regardless, try the following. 无论如何,请尝试以下方法。

ready = ($) ->
    changeEvent = (e) ->
        value = $(this).val()
        if value is not true
            $("#some-element").show()
        else
            $("#some-element").hide()
    $(".radio-button")
        .on("change", changeEvent)
        .each -> $(this).change()

jQuery ready

This binds the change event to the selector, then immediately triggers that event for each element. 这会将change事件绑定到选择器,然后立即触发每个元素的事件。

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

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