简体   繁体   中英

wrap $ in span using jQuery

I'm trying to wrap any dollar signs $ in a span so that I can style them accordingly, without having to go back through and editing each $ I find on the page. The code I've tried to use was for ampersands, and works perfect for ampersands, but I can't get it to work correctly with a dollar sign!

What am I doing wrong here? I've tried using just the $ symbol, and &#36; , but neither are giving me the results needed. Instead it doesn't touch the $ that is wrapped in the <p> , but instead adds it right before the closing </p> .

JSFiddle: https://jsfiddle.net/tk8og3Ln/

HTML:

<p>Cabana Tanning Lotion: $32.00</p>

jQuery:

(function($) {
  $.fn.money = function() {
    return this.each(function() {
      var element = $(this);
      var html = element.html();
      element.html(html.replace(/$/gi, '<span class="money">$</span>'));
    });
  };
})(jQuery);

$('p').money();

CSS:

.money {
  font: italic 1.3em Baskerville, Georgia, serif;
  color: #666;
  padding-right: 5px;
}

$ is RegExp symbol for end of line. You can use "$" or escape $ /\\$/ .

Going off of the answer from @guest271314, I also needed to make sure to wrap the code in a document.ready function to allow WordPress to initialize the jQuery. Here is the finished code.

jQuery(document).ready(function( $ ) {
  $.fn.money = function() {
    return this.each(function() {
      var element = $(this);
      var html = element.html();
      element.html(html.replace(/\$/gi, '<span class="money">$</span>'));
    });
  };

$('p').money();

});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM