开发者

Javascript replace text after an underscore

开发者 https://www.devze.com 2023-02-24 04:21 出处:网络
I am trying to replace some text after an underscore in a filename. Example filename: FileName_true.png. I need to change it to FileName_false.png.

I am trying to replace some text after an underscore in a filename.

Example filename: FileName_true.png. I need to change it to FileName_false.png.

Basically, i have an ima开发者_开发技巧ge that i want to change when you click on it. (color to black and white and vice versa). I thought about using a toggle in JQuery but i wasn't sure that i could do it with like 5 images without duplicating the code 5 times.

My thinking was to create a function that uses a regex to capture the 'true' or 'false in the file name of the image you clicked on and replace it with the alternate.

What are your thoughts on accomplishing this? I would like this done in PHP if possible, but if not then JavaScript/JQuery. Thanks for any help! And let me know if you have any questions.


filename = filename.replace('_true','_false');

neither jQuery nor regexp necessary

<img src="FileName_true.png"
onclick="this.src=(this.src.indexOf('_true')!=-1)?this.src.replace('true','false'):this.src.replace('false','true')" />

is what I could come up with at this late hour

To do this in php would be plain silly and would need a cookie


The answer by mplungjan is great, but let me suggest some alternatives. Image swaps are best done with a sprite, so that there is never any delay switching between the images. Put both versions of the image side by side in a single file. Set that image to be the background of a div, and adjust the background position to display one or the other image.

Suppose "pic1_bw_color_sprite.png" was a 75x75 color image, with a 75x75 b/w image below it, making the final image 75px wide and 150px high. Set up your css like this:

#pic1
{
    background-image: url(pic1_bw_color_sprite.png);
    height: 75px;
    width: 75px;
}
#pic1.bw
{
    background-position: 0px -75px;
}

Then some simple jQuery to make it all work:

$("#pic1").click(function()
{
    $(this).toggleClass("bw");
});

Try it here: http://jsfiddle.net/gilly3/B7esz/

As far as duplicating the code, that is one thing that jQuery is very good at avoiding. Just use a selector that includes every class that needs the behavior:

$("#pic1,#pic2,#pic3,#pic4").click(...);
// or
$(".bwSwap").click(...);

To store the current state in the form so that you can update your database, you need to get a reference to your form element, then set the value property (or .val() in jQuery).

$("#pic1").click(function()
{
    $(this).toggleClass("bw");
    $("#pic1isBW").val($(this).hasClass("bw"));
});
0

精彩评论

暂无评论...
验证码 换一张
取 消