简体   繁体   English

将变量从html传递到javascript

[英]pass variable from html to javascript

<%= semantic_form_for :.........  do |f| %>
<%= f.inputs do%>
    <%= pluralize @size, 'Profitable Routes to test'%>
    <p>User id: <%= @id %><p>
    ....

<title> audio player</title>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
    <link href="/skin/pink.flag/jplayer.pink.flag.css" rel="stylesheet" type="text/css" />

    <script type="text/javascript">
    $(document).ready(function(){
        var u_id = document.getElementById('id')
        $("#jquery_jplayer_1").jPlayer({
            ......
                ......
                ......
                .......
        });
    });
        //]]>
    </script> 

I want to pass the User id to javascript, i'm trying to do it with this: var u_id = document.getElementById('id') but it says that u_id is null, who can i pass it? 我想将User id传递给javascript,我正在尝试使用此方法: var u_id = document.getElementById('id')但它说u_id为null,我可以将其传递给谁? Thanks! 谢谢!

You should write the variable directly in the JavaScript code: 您应该直接在JavaScript代码中编写变量:

var u_id = <%= @id %>;

Actually when you use document.getElementById() in JavaScript you get a DOM element. 实际上,当您在JavaScript中使用document.getElementById() ,您将获得一个DOM元素。 And not the variable @id . 而不是变量@id The variable @id doesn't event exist for JavaScript. 变量@id对于JavaScript不存在。

Why? 为什么?

I guess you're using Rails. 我想您正在使用Rails。 @id is a Rails variable. @id是Rails变量。 Rails compiles the templates (on the server) before sending the final html page to the user. 在将最终的html页面发送给用户之前,Rails会编译模板(在服务器上)。 It means it replaces all the <% %> by the results of each block which are plain text. 这意味着它将用纯文本格式的每个块的结果替换所有<% %>

The JavaScript is then run on the client browser. 然后,JavaScript将在客户端浏览器上运行。 It's not aware of Rails. 它不了解Rails。

When you do var u_id = <%= @id %>; 当你做var u_id = <%= @id %>; Rails compiles it in something like var u_id = 198297; Rails以类似var u_id = 198297; which is send to the client browser. 发送到客户端浏览器。 Then JavaScript is happy, the variable is correctly set. 然后,JavaScript高兴了,正确设置了变量。

u_id is the dom element . u_id是dom元素。 you should select a attr of this element 您应该选择此元素的属性

u_id.value

or 要么

u_id.innerHTML

in jquery : 在jQuery中:

u_id.val()
u_id.html()

document.getElementById('id') is the element, not its value. document.getElementById('id')是元素,而不是其值。 You should use something similar to 您应该使用类似

id = document.getElementById('id').innerHTML;

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

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