2014-03-12 24 views
0

HTML:阿尔特文件名的基础上,选择框

<div id="product-main-image"> 
    <img src="path/to/image.jpg"> 
</div> 
<select id="selection" name="selection"> 
    <option value="someval1"> Red </option> 
    <option value="someval2"> Blue </option> 
</select> 

JS:

jQuery("#selection").change(function() { 
     var str = ""; 
     jQuery("#selection option:selected").each(function() { 
      str += jQuery(this).text() + " "; 
     }); 
     str = str.toLowerCase().trim(); //red or blue 

     var new_img = jQuery("#product-main-image img").attr('data-zoom-image'); //here i get path/to/image.jpg 
     //what now?? 
}); 

结果: 我应该得到的路径/到/图像红色。 jpg或path/to/image-red.jpg

N OTE:扩展可JPG,JPEG,PNG,GIF等

+0

尝试'new_img = new_img.replace(/(\。[az] {3,4})$ /,' - '+ str +'$ 1')'替换'。 ext'与'-str.ext'(任何3或4字符扩展名) – SmokeyPHP

+1

好,它的工作。很快会接受你的回答:) – RhymeGuy

回答

0

你可以基于一个相当简单的正则表达式替换像这样:

var str = 'red'; 
var new_img = 'path/to/image.jpg'; 
new_img = new_img.replace(/(\.[a-z]{3,4})$/,'-'+str+'$1'); 
console.log(new_img); //"path/to/image-red.jpg" 

(你应该能够复制并粘贴了这一切代码作为测试版本到控制台)