簡體   English   中英

jQuery text()和show()無法正常工作(RoR應用程序)

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

我想對購物車中的物品數量進行自定義和簡單檢查。

首先,我在菜單元素之一中使用占位符div加載頁面:

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

然后在我的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();
            }
        });
    }
});

請求的AJAX已成功執行,並且警報顯示了預期的文本(“(count)”,再說“(3)”,這意味着我的購物車中有3件商品)。

但是$("#items_count").empty().html(items_count_new_content); $("#items_count").show(); 即使功能很簡單,它似乎也根本無法工作。 而且,過去我已經成功使用了很多次...

我試圖用html()替換text()沒有成功。

有什么想法可能是這里的問題嗎?

謝謝

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

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

調試后,我注意到頁面上有2個菜單,而不是1個(普通菜單和粘滯菜單)。 所以我的問題是使用id作為元素的選擇器。 這導致jQuery僅替換了粘性菜單的內容(在頁面頂部是不可見的),因為我們應該為DOM中的每個元素擁有唯一的ID。

我通過用$(".items_count_div")替換$("#items_count")來解決我的問題

希望對遇到類似問題的人有幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM