我的页面上有这样的按钮(用于显示购物车中的当前总数):
<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);
}
关于javascript - 使用 JavaScript 更新按钮上的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40248799/