简体   繁体   English

如何在Rails视图中的条件内调用javascript函数?

[英]How to call a javascript function inside a conditional in Rails view?

I'd like to know how to call a JavaScript function from within an <% if statement %> in a Rails view. 我想知道如何在Rails视图中的<% if statement %>中调用JavaScript函数。 I don't really know if it's even possible. 我真的不知道是否有可能。

home.html.erb: home.html.erb:

<script type="text/javascript"> 
function my_javascript_function() {
    return false;
}
</script>

<!-- some code before -->
<% if my_javascript_function %>
    <li>
        <a href="/link/">
            Link
        </a>
    </li> 
<% end %>
<!-- some code after -->

UPDATE: After Chen's answer, I realized that what I was doing was wrong, and instead of using <% if statement %> to create my element, I'm just using jQuery for this now. 更新:在Chen的回答之后,我意识到我在做错了,而不是现在使用jQuery来代替使用<% if statement %>来创建我的元素。 The code ended up like this: 代码最终如下所示:

$(document).ready(function() {
    if(/* my_conditions */) {
        $('#my_list_element').prepend('<li><a href="/link/">Link</a></li>');
    }
});

So, when the page is loaded, it creates my element from javascript (jQuery). 因此,在加载页面时,它将通过javascript(jQuery)创建我的元素。 In my case, I used .prepend() because I needed it to be the first element within the list. 就我而言,我使用.prepend()是因为我需要它成为列表中的第一个元素。

I think you got it wrong. 我想你错了。

Javascript is rendered on the client side, while the rails part is rendered on the server side. Javascript是在客户端渲染的,而rails部分是在服务器渲染的。 When the server tries to render your 'if' statement it does not know nothing about the javascript function. 当服务器尝试呈现“ if”语句时,它对javascript函数一无所知。

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

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