Rails呈现ajax错误

时间:2013-04-22 20:50:35

标签: ruby-on-rails ruby ajax jquery

我就是这样的index.html.erb

<div id="carte_items">
  <ul id="nav">
    <li id="category_14" class="category-group">
      <p class="category">Pizzas tradicionais</p>

      <ul class="tags">
        <li>
          <div class="links" style="display: none;">
            <a href="#" data-method="delete" data-remote="true" rel="nofollow">
              <i class="icon-trash icon-white"></i>
            </a>

            <a href="#" data-remote="true">
              <i class="icon-pencil icon-white"></i>
            </a>
          </div>
          Pizza X
        </li>

        <li>
          <div class="links" style="display: none;">
            <a href="#" data-method="delete" data-remote="true" rel="nofollow">
              <i class="icon-trash icon-white"></i>
            </a>

            <a href="#" data-remote="true">
              <i class="icon-pencil icon-white"></i>
            </a>
          </div>
          Pizza X
        </li>
      </ul>
    </li>
  </ul>
</div>

所以,我在我的products.js.coffee

$("ul.tags li").on('mouseover', () ->
 $(this).find('.links').show()
).on('mouseout', () ->
 $(this).find('.links').hide()
)

当我第一次访问时,我的index.html.erb一切正常。但是对于仍然像我第一次访问时那样工作的链接,我必须将products.js.coffee中的源复制到index.js.erb下面。就像当我使用我的搜索时,使用ajax进行搜索,如果我不像below那样复制源,那么&#34; .links&#34;不再显示了。

他们就像那个

那样是index.js.erb
$("#carte_items").html("<%= j(render 'carte_items') %>");
$("ul.tags li").on('mouseover', function() {
  return $(this).find('.links').show();
}).on('mouseout', function() {
  return $(this).find('.links').hide();
});

为什么必须复制源?只需使用文件products.js.coffee中的源代码就可以正常工作而无需复制到index.js.erb ??

感谢您的帮助。

2 个答案:

答案 0 :(得分:2)

试试这个:

$("ul.tags").delegate('li', 'mouseover', () ->
 $(this).find('.links').show()
).delegate('li', 'mouseout', () ->
 $(this).find('.links').hide()
)

或:

$("ul.tags").on('mouseover', 'li', () ->
 $(this).find('.links').show()
).on('mouseout', 'li', () ->
 $(this).find('.links').hide()
)

答案 1 :(得分:2)

来自jQuery API docs:

.on()

描述:将一个或多个事件的事件处理函数附加到所选元素。

.delegate()

描述:根据一组特定的根元素,为现在或将来与选择器匹配的所有元素的一个或多个事件附加一个处理程序。

代表:“......现在或将来”。因此,请尝试使用delegate()代替on()

希望它有效!