查找和替换 jquery
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/233922/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Find & replace jquery
提问by Chris J Allen
I have this code to give me a rollover on submit buttons, and I'm trying to make it more generic:
我有这个代码可以让我在提交按钮上滚动,我试图让它更通用:
$('.rollover').hover(
function(){ // Change the input image's source when we "roll on"
srcPath = $(this).attr("src");
srcPathOver = ???????
/*need to manipulate srcPath to change from
img/content/go-button.gif
into
img/content/go-button-over.gif
*/
$(this).attr({ src : srcPathOver});
},
function(){ // Change the input image's source back to the default on "roll off"
$(this).attr({ src : srcPath});
}
);
Two things really,
真的有两件事,
I want to learn how manipulate the srcPath
variable to append the text '-over' onto the gif filename, to give a new image for the rollover. Can anyone suggest a way to do this?
我想了解如何操作srcPath
变量以将文本“-over”附加到 gif 文件名上,从而为翻转提供新图像。谁能建议一种方法来做到这一点?
Also, can someone tell me if this code could be refined at all? I'm a bit new to jQuery and wondered if the syntax could be improved upon.
另外,有人能告诉我这个代码是否可以改进吗?我对 jQuery 有点陌生,想知道是否可以改进语法。
Many thanks.
非常感谢。
回答by jcampbell1
$('.rollover').hover(
function(){ // Change the input image's source when we "roll on"
var t = $(this);
t.attr('src',t.attr('src').replace(/([^.]*)\.(.*)/, "-over."));
},
function(){
var t= $(this);
t.attr('src',t.attr('src').replace('-over',''));
}
);
回答by LorenzCK
To manipulate the file name and append "-over" you simply have to do some Javascript string manipulation, like this:
要操作文件名并附加“-over”,您只需执行一些 Javascript 字符串操作,如下所示:
function appendOver(srcPath){
var index = s.indexOf('.');
var before = s.substr(0, index);
var after = s.substr(index);
return before + "-over" + after;
}
This should return the original filename (in all possible formats) and add the '-over' string just before the extension dot.
这应该返回原始文件名(所有可能的格式)并在扩展点之前添加“-over”字符串。
回答by Matt Ephraim
You should be able to use a regex replace to modify your source path. Like this:
您应该能够使用正则表达式替换来修改源路径。像这样:
srcPathOver = srcPath.replace(/([^.]*)\.(.*)/, "-over.");
More on JavaScript regexes here
更多关于 JavaScript 正则表达式在这里
As far as how you're doing it, I'd make sure that you define your srcPath variable like this
至于你是怎么做的,我会确保你像这样定义你的 srcPath 变量
var srcPath;
$('.rollover').hover(...
The code you have above makes it look like srcPath is a global variable, which is not what you want.
您上面的代码使它看起来像 srcPath 是一个全局变量,这不是您想要的。