Javascript replace text after an underscore

China☆狼群 提交于 2019-12-25 15:52:44

问题


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 image 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.


回答1:


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




回答2:


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"));
});


来源:https://stackoverflow.com/questions/5614430/javascript-replace-text-after-an-underscore

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!