简体   繁体   中英

Replacing dynamic content jQuery/javascript

I need to do a dynamic replace in a string with jQuery. I have read about using wildcards in selectors, but I want it in a string.

Considering this HTML:

<style type="text/css">@import url('css/another.css');</style>
<style type="text/css">@import url('css/stylesMQ.css');</style>

And I have this function in jQuery:

function adjustStyle(width) {
    width = parseInt(width);
    if (width < 701) {
        $('style:contains("MQ")').text(function () {
        return $(this).text().replace("MQ.css", "400MQ.css");
        });
    } else if ((width >= 701) && (width < 900)) {
        $('style:contains("MQ")').text(function () {
        return $(this).text().replace("MQ.css", "800MQ.css");
        });         
    } else {
       $('style:contains("MQ")').text(function () {
        return $(this).text().replace("MQ.css", "MQ.css");
        });         
    }
}

This function is part of an entire jQuery that changes an @imported css depending of screen size.


ERROR

It works, but when I start playing with the screen size I get something like:

@import url('css/styles800800800800400400400400400400400400400400MQ.css');

I can't figure how can I tell jQuery to replace also the number .
I suppose that I need something like:

.replace("styles*MQ.css", "styles400MQ.css");

TIPS:

  • I'm not using mediaqueries because my client is Fred Flinstone, he uses IE7 and don't wants pollyfills because the extra loading time and because thinks they're the demon.
  • There are other @imported CSS's in the page
  • I don't know the entire path for the CSS nor the folder, only the name (that's the reason I want to make replacing instead of write the relative path location of the new CSS.)
  • I can change the name of any of these CSS.

Instead of .replace("MQ.css", "MQ.css"); try something like

.replace(/\d*MQ\.css/, "MQ.css");
.replace(/\d*MQ\.css/, "400MQ.css");
$('style:contains("MQ")').text(function () {
    return $(this).text().split('/')[0]+"/400MQ.css";
});

I would use

$('style:contains("MQ")').text(function (pos, value) {
        return value.replace(/styles(400|)MQ\.css/, "styles800MQ.css");
});

same solution changing the expected expression (400, 800, '')

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