我希望5 left
做-1
例如成为4 left
。
HTML
<span class="small">5 left</span>
的jQuery
// Store the 5 left in "numberStock" variable
var numberStock = parseInt($(".small:first").text());
// Subtract with "numberStock -1"
var minusStock = numberStock - 1;
// Here comes the issue, how do I add the new content?
$(".small:first").attr(minusStock "left");
问题
如何添加新号码库号4
和文字left
?
答案 0 :(得分:1)
使用String#replace
方法和回调函数。
// use text method with callback where second
// argumnet is old text
$(".small:first").text(function(i, txt) {
// replace text with decremented value
return txt.replace(/\d+/, function(m) {
return m - 1;
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="small">5 left</span>
更新:使用纯JavaSript执行类似的操作。
// since you just want the first element use
// querySelector otherwise you need to use
// querySelectorAll and then need to iterate
// over them
var ele = document.querySelector(".small");
// update text content of span element
ele.textContent = ele.textContent.replace(/\d+/, function(m) {
return m - 1;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="small">5 left</span>
答案 1 :(得分:1)
您可以使用替换:
// Store the 5 left in "numberStock" variable
var numberStock = parseInt($(".small:first").text());
// Subtract with "numberStock -1"
var minusStock = numberStock - 1;
console.log(minusStock);
// Here comes the issue, how do I add the new content?
var original = $(".small:first").text();
var toAdd = original.replace(original[0], minusStock);
$(".small:first").text(toAdd);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="small">5 left</span>
答案 2 :(得分:1)
普通Javascript中的解决方案
Array.prototype.forEach.call(document.getElementsByClassName('small'), function (a) {
a.innerHTML = a.innerHTML.replace(/\d+/, function (v) {
return v - 1;
});
});
<span class="small">5 left</span>
答案 3 :(得分:-1)
我不确定我是否理解你的问题,但如果我在这里做的是一种方法,这与你想要达到的目标非常接近
var numberStock = parseInt($('.small').text())
var minusStock = numberStock - 1;
$('.small').text(minusStock + ' left');
如果你想用它来测试,这里有一个小提琴
https://jsfiddle.net/09wcjp7b/