简体   繁体   English

jQuery text()和show()无法正常工作(RoR应用程序)

[英]jQuery text() and show() not working ( RoR application)

I want to implement a custom and simple check of the number of items that I have in the cart. 我想对购物车中的物品数量进行自定义和简单检查。

First, I load my page with a place holder div in one of my menu elements: 首先,我在菜单元素之一中使用占位符div加载页面:

<div id="items_count" style="display:none;">(count)</div>

Then in my javascript file (application.js) I have the following code: 然后在我的javascript文件(application.js)中,有以下代码:

$(document).ready(function () {
  $items_count_element = $("#items_count");
  if ($items_count_element.length > 0 )
  {
    $.ajax({
        url: '/get_items_count',
        type: 'GET',
        dataType: 'json',
        success: function (response) {
            // Construct the new string to display
            items_count_new_content = "(" + response.items_count + ")";

            // Printout to verify that we point to the correct div
            alert($("#items_count").text());
            // Verify the new string to display
            alert(items_count_new_content);


            // Empty the div element and replace the content with the new string
            $("#items_count").empty().text(items_count_new_content);

            // Remove display : none
            $("#items_count").show();
            }
        });
    }
});

The AJAX requested is executed with success, and the alerts display the expected text ( "(count)" and lets's say "(3)", which means i have 3 items in the cart ). 请求的AJAX已成功执行,并且警报显示了预期的文本(“(count)”,再说“(3)”,这意味着我的购物车中有3件商品)。

But $("#items_count").empty().html(items_count_new_content); 但是$("#items_count").empty().html(items_count_new_content); and $("#items_count").show(); $("#items_count").show(); seem to not work at all, even if the functions are simple enough. 即使功能很简单,它似乎也根本无法工作。 Moreover, I've used them many times in the past with success... 而且,过去我已经成功使用了很多次...

I've tried to replace text() with html() with no success. 我试图用html()替换text()没有成功。

Any ideas what may be the problem here ? 有什么想法可能是这里的问题吗?

Thanks 谢谢

在jQuery中,您可以使用val更改值:

$("#items_count").empty().val(items_count_new_content);

After debugging, i noticed that i had 2 menus on the page instead of one ( the normal menu and the sticky menu ). 调试后,我注意到页面上有2个菜单,而不是1个(普通菜单和粘滞菜单)。 So my problem was the usage of the id as the selector my element. 所以我的问题是使用id作为元素的选择器。 This caused that the jQuery replaced the content only for the sticky menu ( Which is invisible in the top of the page ), since we are supposed to have unique ids for each element in the DOM. 这导致jQuery仅替换了粘性菜单的内容(在页面顶部是不可见的),因为我们应该为DOM中的每个元素拥有唯一的ID。

I fixed my issue by replacing $("#items_count") by $(".items_count_div") 我通过用$(".items_count_div")替换$("#items_count")来解决我的问题

I hope it'll help whoever encounter similar problem. 希望对遇到类似问题的人有帮助。

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

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