如何使用 jQuery 替换和/或删除文本或 div [关闭]

问题描述 投票:0回答:1

我有这段代码,我必须按原样使用它(如下)。我想隐藏、删除所有这些文本,然后写下我自己的文本。或者只是替换一个 Div 并删除另一个,等等......你明白了......

<div class="a-section a-spacing-top-base">
<b>Returning your item:</b><br>Go to "Your Account" on Amazon.com, click "Your Orders" and then click the "seller profile" link for this order to get information about the return and refund policies that apply.<br>Visit <a href="https://www.amazon.com/returns">https://www.amazon.com/returns</a> to print a return shipping label.  Please have your order ID ready. 
</div>
<div class="a-section a-spacing-top-base">
<b>Thanks for buying on Amazon Marketplace</b>. To provide feedback for the seller please visit <a href="http://www.amazon.com/feedback">www.amazon.com/feedback</a>. To contact the seller, go to Your Orders in Your Account. Click the seller's name under the appropriate product. Then, in the "Further Information" section, click "Contact the Seller."
 </div>

非常感谢您的帮助。

javascript jquery
1个回答
0
投票

如果能再给点代码就好了。我猜这 2 个 DIV 是嵌套的,是吗?由于您的信息非常模糊,正如我所说,我为我的代码片段假设了两件事(主要是为了能够更好地展示如何将您自己的文本放入相应的 DIV 中):

  • 两个DIV有一个容器(嵌套)
  • 该容器中没有其他元素(否则您可以使用
    :nth-child()
  • 应该删除/替换两个 DIV 中的所有内容

因此,为了您的意图(删除/替换文本),您可以使用 jQuery 中的 text() 方法html() 方法。两者都允许您替换文本或只是删除它。 再次,DIV 中的所有内容都被替换/删除。

jQuery API 文档:

.text() - https://api.jquery.com/text/
.html() - https://api.jquery.com/html/

/*
  The button is only for demonstration purpose.
*/
$( '#btn-1' ).click( function() {
    /* You only need this part, i.e. something like this */
    $( '.wrapper-or-whatever .a-section:first-child' ).text( '<i>I cannot use HTML here.</i>' );
} ); 
/*
  The button is only for demonstration purpose.
*/
$( '#btn-2' ).click( function() {
   /* You only need this part, i.e. something like this */
   $( '.wrapper-or-whatever .a-section:last-child' ).html( '<i>I can use HTML here.</i>' );
} );
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="wrapper-or-whatever">
    <div class="a-section a-spacing-top-base">
        <b>Returning your item ...</b>
    </div>
    <div class="a-section a-spacing-top-base">
        <b>Thanks for buying ...</b>
    </div>
</div>
<br>
<button id="btn-1">Change text of 1st DIV using .text()</button>
<br><br>
<button id="btn-2">Change text of 2nd DIV using .html()</button>

最后,如果您想知道为什么需要容器,请发表评论,我将添加一个示例。
综上所述,编码愉快。

编辑: 我错过了你写的“或删除一个 DIV”。所以如果你想知道如何做到这一点,也请发表评论,至于现在我只解释了如何通过删除/替换文本来做到这一点。

© www.soinside.com 2019 - 2024. All rights reserved.