Dynamic Javascript in my .html.erb

强颜欢笑 提交于 2020-01-14 09:21:30

问题


I'm struggling with some Javascript in my first rails application.

Partial: _care_point.html.erb

<script>
  $(function() {
    $( ".draggable" ).draggable({grid: [50, 20]});
    $( ".node_input").each (function() {
      $(this).hide();
    });
    $("#<%="node.#{care_point.id}" %>").live('dblclick', function(){
      console.log('moo');
      jQuery(this).hide();
      jQuery('.node_input', jQuery(this).parent()).show();
    });
  });
</script>
<div id=<%="care_point.#{care_point.id}" %> class='draggable node_chin'>
  <div id=<%="node.#{care_point.id}" %> class='node'><%= care_point.body %>
  </div>
  <textarea class='node_input'><%= care_point.body %></textarea>
</div>

This is the output:

    <script> 
  $(function() {
    $( ".draggable" ).draggable({grid: [50, 20]});
    $( ".node_input").each (function() {
      $(this).hide();
    });
    $("#node.1").live('dblclick', function(){
      console.log('moo');
      jQuery(this).hide();
      jQuery('.node_input', jQuery(this).parent()).show();
    });
  });
</script> 
<div id=care_point.1 class='draggable node_chin'> 
  <div id=node.1 class='node'>Moo foo
  </div> 
  <textarea class='node_input'>Moo foo</textarea> 
</div>

I first added the dblclick event listener classbased, but that caused it to be added multiple times. This made me change it to a id based approach, but now it does not work. Is it because I try to dynamically build up the id?

Is this even the righ place to do this kind of thing?


回答1:


The problem is here:

 $("#'#node.2'").live('dblclick', function(){

To work it must be:

 $('#node.2').live('dblclick', function(){

i'm no expert of ruby but you must change something here:

 $(<%="'#node.#{care_point.id}'" %>).dblclick(function(){

I'd try (but i'm guessing - edited)

$('#<%=node.#{care_point.id} %>').dblclick(function(){

EDIT - Try removing the dots in the ids of th HTML: look at this fiddle http://jsfiddle.net/JeHuD/

replace

#<%=node.#{care_point.id} %>

with (both in the jquery selector and in the HTML (also consider that your id in the html should have double quotes like this: id="node1")

#<%=node#{care_point.id} %>

FINAL EDIT - in the jquery selector you must escape dots withdoubole backslashes: here is the updated fiddle that works with the dot http://jsfiddle.net/JeHuD/1/




回答2:


Try the following:

$("#<%="node.#{care_point.id}" %>").live('dblclick', function(){
      console.log('moo');
      jQuery(this).hide();
      jQuery('.node_input', jQuery(this).parent()).show();
    });


来源:https://stackoverflow.com/questions/6355784/dynamic-javascript-in-my-html-erb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!