如何只替换div中存在的部分内容

时间:2015-11-26 15:15:40

标签: jquery

我已经在我的div下面,我需要替换文本仅限Eigth Dollars 并保留其余的以编程方式

<div class="dtls_order_ftr">
                            <p class="converter">(Total Amount in words: Eigth Dollars only)<br>
<span>(Note: Calculation of taxes and charges made as applicable for individual items)</span>
<span>(Note: Total amount is inclusive of all applicable tax and charges)</span></p>

                        </div>

我试过

var setmyvalue = 'Five Dollars Only'    

$(".converter").text(setmyvalue);

但它取代了整个内容,请你告诉我怎么做?

http://jsfiddle.net/qfe5xgjs/3/

3 个答案:

答案 0 :(得分:2)

$(".converter").text(setmyvalue);您使用新值(setmyvalue)更改所有转换器..所以请尝试使用

var setmyvalue = 'Five Dollars Only';  // value we want to change to    
var replacevalue = $(".converter").text().replace('Eigth Dollars  only',setmyvalue);  // replace the old value with the new one
$(".converter").text(replacevalue); // put it in the converter after replace it

DEMO

答案 1 :(得分:1)

您需要使用.replace(),然后设置container文字JS Fiddle

var setmyvalue = 'Five Dollars Only',
  text = $(".converter").text();

text = text.replace('Eigth Dollars only', setmyvalue);
$(".converter").text(text);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div class="dtls_order_ftr">
  <p class="converter">(Total Amount in words: Eigth Dollars only)
    <br>
    <span>(Note: Calculation of taxes and charges made as applicable for individual items)</span>
    <span>(Note: Total amount is inclusive of all applicable tax and charges)</span>
  </p>

</div>

答案 2 :(得分:1)

像这样创建一个span占位符:

<div class="dtls_order_ftr">
                            <p class="converter">(Total Amount in words: <span id="amountInWords">Eigth Dollars only</span>)<br>
<span>(Note: Calculation of taxes and charges made as applicable for individual items)</span>
<span>(Note: Total amount is inclusive of all applicable tax and charges)</span></p>

                        </div>

然后:

var setmyvalue = 'Five Dollars Only'    

$("#amountInWords").html(setmyvalue);