2011-01-22 85 views
0

我遇到以下问题。由于有许多业务规则,我决定将这些功能作为js自动更新。Javascript无法获得运营价值

在我看来,我有: 这是一个表

(<%= javascript_include_tag 'people'%>) 

     <th>Name</th> 
     <th>Money</th> 
     <th>Money Comment</th> 
    </tr> 
    <% @counter = 0 %> 
    <% @people.each do |p| %> 
    <% @counter += 1 %> 
    <tr> 
    <%= form_for(:p) do |f| %> 
    <th><%= f.label(p.name) %></th> 
    <th><label for="<%= "money_" + @counter.to_s %>"> <%= f.select(:money, 1..10, :selected => p.money)%></label></th> 
    <th><label for="<%= "comment_" + @counter.to_s %>"> <%= f.label(p.money_comment, :disabled => 'disabled')%></label></th> 
    <% end %> 
    <% end %> 

内,在JavaScript函数如下:

function change_people() { 
    money1 = $('money_1').getValue(); 
    if (money1 == 10) { 
    $('comment_2').setValue("I know what you're doing you mofo"); 
    } 
    else { 
    $('comment_2').setValue(""); 
    } 
} 

document.observe('dom:loaded', function() { 
    change_people(); 
    $('money_1').observe('change', change_people); 
}); 

,但由于某种原因,它不断告诉我没有关系不知道我的意思是“money_1”。我检查html源代码并编译视图,我是否在js中错误地引用了元素?

感谢您的帮助!

+0

请编辑你已经包括了代码使用的代码标记({})。 – 2011-01-22 17:43:16

回答

0

看起来,如果你需要一个选择:

<th id="<%= "money_" + @counter.to_s %>"> 
<label for="<%= "money_" + @counter.to_s %>"> 
    <%= f.select(:money, 1..10, :selected => p.money)%> 
</label> 
</th> 

现在你已经给原型搜索并找到正确的元素(选择与您要查找的值)的能力,你传递给$()函数调用的getValue():

function change_people() { 
    // Note the "#" on #money_1, which is an ID selector 
    // the space " " between is a descendant element selector 
    money1 = $($$('#money_1 select')).getValue(); 
    if (money1 == 10) { 
     // do stuff 
    } else { 
     // do other stuff 
    } 
} 

如果你正在寻找遍历表中所有的钱选择值,你反而会想使用一个类;您只允许为每个ID使用一个元素,但按规则分类则按属性分组。所不同的是:

<th class="money_select"> 
<label for="<%= "money_" + @counter.to_s %>"> 
    <%= f.select(:money, 1..10, :selected => p.money)%> 
</label> 
</th> 

然后在你的JavaScript:

function change_people() { 
    // Note the "." on .money_1, which is a class selector 
    // the space " " between is a descendant element selector 
    $$('.money_select select').each(function(element){ 
     if ($(element).getValue() == 10) { 
      // do stuff 
     } else { 
      // do other stuff 
     } 
    }); 
} 
+0

谢谢贾里德,只是试图将此添加到js,但它给了我同样的错误。现在它只是改变了它告诉我的错误名称。 money1 = $('#money_1')。getValue(); Uncaught TypeError:无法调用null的方法'getValue' – Lievcin 2011-01-22 17:51:16