简体   繁体   中英

jQuery - Replace a word in a child div if parent div contains a specific word

What I'm trying to do is change a specific word in a div I've added if the parent div contains a specific word;

<p class="days">Stock, 1 piece remaining.</p>

I have to add an additional workaround to add another div for more information using the prepend function:

$(".days").append('<div class="daysAddiontalInfo">Explaination of stock 1 piece</div>');

I'd like the following; if my parent div (.days) contains the number 1 - I need it to show 1 piece, but if it contains the number 2,3,4 or 5 I need it to show 2,3,4 or 5 pieces.

I got no idea how to expand the code to do this specific task.

Thanks in advance for your time and feedback!

Here's an example solution:

var $days = $(".days");
var pieces = $days.text().match(/\d/);

$days.append('<div class="daysAddiontalInfo">Explaination of stock '+pieces+' piece</div>');

And a working code: http://jsfiddle.net/367vvq1a/

Also, to take a plural form into consideration - and account for having more than one .days element - you can do it like this:

$(".days").each(function () {
    var piecesMatch = $(this).text().match(/\d+/);
    if (piecesMatch) {
        var piecesCount = parseInt(piecesMatch[0]);
        var piecesText = piecesCount + ((piecesCount > 1) ? ' pieces' : ' piece');
        $(this).append('<div class="daysAddiontalInfo">Explaination of stock '+piecesText+'</div>');
    }
});

And here's the demo: http://jsfiddle.net/p02wvtvs/1/

if you are sure it will be a number then you can use

var number = parseInt($(".days").text());
$(".days").append('<div class="daysAddiontalInfo">Explaination of stock "+ number +" piece</div>');

otherwise you can put specific word in span and get its value

<p class="days">Stock, <span>1</span> piece remaining.</p>

and in javascript

var word = $(".days span').text();
$(".days").append('<div class="daysAddiontalInfo">Explaination of stock "+ word +" piece</div>');

You can provide a function to the append() method which will inspect the HTML of each .days element individually. From there you can use a regex to match on the 1 piece , 2 pieces etc strings, and return the new HTML to append. Try this:

$('.days').append(function(i, html) {
    var matches = /(\d pieces?)/gi.exec(html);
    return '<div class="daysAddiontalInfo">Explaination of stock ' + matches[0] + ' </div>';
});

Example fiddle

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