javascript - 使用 JavaScript 更新按钮上的文本

标签 javascript jquery html

我的页面上有这样的按钮(用于显示购物车中的当前总数):

    <div class="col s2 offset-s4 valign" id="shoppingCart">
        <a class="waves-effect waves-teal btn-flat no-margin white-text right" th:inline="text"><i class="material-icons right">shopping_cart</i>[[@{${total}+' руб'}]]</a>
    </div>

用于更新该按钮上总数的写入函数:

function updateShoppingCart(newTotal) {
    var $div = $("#shoppingCart");

    var $a = $("<a class='waves-effect waves-teal btn-flat no-margin white-text right'></a>");
    var $i = $("<i class='material-icons right'>shopping_cart</i>");
    var $string = formatDecimal(newTotal,',','.') + " руб";

    $a.append($i);
    $a.append($string);

    $div.children().remove();
    $div.append($a);
}

但是它不起作用。请帮助查找错误或我做错了什么。

最佳答案

设置$div = $('#shoppingCart');; 效率更高。在全局范围内并使用该 var 代替。这样,每次调用函数时,JS 就不会搜索整个 DOM。

你的东西不起作用,因为你的var非常奇怪。我相信您想要实现的是:

HTML

<a class="waves-effect waves-teal btn-flat no-margin white-text right" th:inline="text">
  <i class="material-icons right">shopping_cart</i>
  <span>[[@{${total}+' руб'}]]</span>
</a>

JS:

function updateShoppingCart(newTotal) {
    var $div = $("#shoppingCart");

    var $a = $("a", $div); //select the <a> within the shoppingcart div
    var $i = $("i", $div); //select the <i> within the shoppingcart div
    var $span = $("span", $div); //select the newly added span
    var newPrice = formatDecimal(newTotal,',','.') + " руб";

    $span.text(newPrice);
}

我保留了 $a$i 作为示例,但我认为您没有必要使用它们或完全替换它们,因为您只需想要更改文本。通过使用跨度,您可以定位价格,而无需替换所有 html。

旁注,$ 通常用于声明 var 是 jquery 对象。在这种情况下,string 不是 jquery 对象,因此 $ 有点奇怪。

顺便说一句,如果你想替换元素中的 html,你应该尝试这样做:

function updateShoppingCart(newTotal) {
    var $div = $("#shoppingCart");

    var newPrice = formatDecimal(newTotal,',','.') + " руб";
    //Create the new HTML as a string, not as an element
    var newHtml= '<a href="#" class="somethingClass"><i>Shopping_cart</i>'+newPrice+'</a>';

    //empties div beforehand current html, no seperate removal needed.
    //Then places the html string within the element
    $div .html(newHtml); 
}

See working JSFiddle here

关于javascript - 使用 JavaScript 更新按钮上的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40248799/

相关文章:

php - 注册后 Facebook 重定向

javascript - IE 权限被拒绝

javascript - jQuery 3.3.1 更新给 Chrome/Safari 错误?

html - div的垂直对齐

javascript - AJAX 和 PHP 发送 "HTTP get request"到同一页面

javascript - 如何重新创建 json 对象

javascript - 使用Ajax、PHP上传PDF文件到MYSQL数据库

javascript - 无法在 DOM 中添加 html 按钮

Javascript,为什么从循环外部和内部打印字符串值没有区别?

HTML:全屏 2x2 表格,每个单元格中都有缩小/拉伸(stretch)(但比例正确)的图像