是否有可能在jQuery中插入文本後範圍。例如,我想在下面的美元符號後更改價格值。跨度後更改文本
<div id="price">
<span>$</span>
10.00
</div>
我可以看到如何做到這一點的唯一方法,是刪除跨度元素(店作爲變量),加上價格值,然後再追加貨幣的價值。看起來很哈克。
是否有可能在jQuery中插入文本後範圍。例如,我想在下面的美元符號後更改價格值。跨度後更改文本
<div id="price">
<span>$</span>
10.00
</div>
我可以看到如何做到這一點的唯一方法,是刪除跨度元素(店作爲變量),加上價格值,然後再追加貨幣的價值。看起來很哈克。
可以使用lastChild
和nodeValue
像以下更改價格。
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="price">
<span>$</span>
10.00
</div>
<script>
var price = $('#price')[0];
price.lastChild.nodeValue = "155.00";
</script>
是的,你可以做到這一點是:
$("#price").contents(":not(span)").text("Text");
只需要添加另外跨度環繞的價格值。
<div id="price">
<span>$</span>
<span id="price-value">10.00</span>
</div>
然後你可以$("#price-value")
來自己操縱那部分。
試試這個
$("#pri").text("100");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="price">
<span id='si'>$</span>
<span id='pri'>10.00</span>
</div>
彼此的方式
<script src="http://code.jquery.com/jquery.min.js"></script>
<div id="price">
<span>$</span>
10.00
</div>
<script type="text/javascript">
$('#price').contents().last()[0].textContent=' 20.00';
</script>
設置文本需要一些老式的JavaScript援助。使用textContent
。
$('#price').contents().filter(function() {
return this.nodeType == 3;
}).last()[0].textContent = 'changed';
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div id="price">
<span>$</span>
10.00
</div>
您可以嘗試insertAfter()jQuery中。
HTML:
<button>Insert span element after span element</button>
<br>
<div id="price">
<span>$</span>
</div>
的jQuery:
$(document).ready(function(){
$("button").click(function(){
$("<span>100</span>").insertAfter("span");
});
});
這樣更容易選擇,我們也可以使用CSS前面加上貨幣符號。這避免了完全使用跨度並允許更改貨幣符號。
CSS例子:
.currency div::before { content: "$" }
.currency.yen div::before { content: "¥" }
和工作代碼片段:
$('#item1').html('10.00');
$('#item2').html('8.80');
$('#item3').html('20.30');
.currency.dollar div::before { content: "$" }
.currency.pound div::before { content: "£" }
.currency {
font-family: monospace;
font-size: 24px;
font-weight: bold;
border: 1px lightgray solid;
width: 8em;
padding: 4px;
text-align: right;
background-color: ghostwhite;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="currency dollar">
<div id="item1"></div>
<div id="item2"></div>
<div id="item3"></div>
</div>
您可以通過訪問(和修改的值),這樣做的持有金額的textnode,如下所示:https://jsfiddle.net/7mdyg LLs/ – techfoobar
爲什麼這會被投下來,並投票結束? –
我想知道爲什麼。根本找不到任何問題。 – techfoobar