如何替换属性 JQuery 中的子字符串
How to replace a substring within an attribute JQuery
在过去的几个小时里,我一直在寻找一种方法来做到这一点,但一无所获。我正在尝试找出一种仅更改属性中的子字符串的方法。我想做的一个例子是改变
<a href="media/gallery/jtnp/JT.JPG" rel="shadowbox[JTNP]" title="Joshua tree" class="shaddowimages"><img id="JTth" src="media/gallery/jtnp/b_thum/JTthumb.JPG" alt="A small Joshua tree"></a>
自
<a href="media/gallery/jtnp/JT.JPG" rel="shadowbox[JTNP]" title="Joshua tree" class="shaddowimages"><img id="JTth" src="media/gallery/jtnp/s_thum/JTthumb.JPG" alt="A small Joshua tree"></a>
这是我到目前为止所拥有的,但是当我尝试按下按钮 #changethumb 时没有任何反应。
$(document).ready(function() {
var count = 0;
$('#changethumb').click(function() {
if (count === 0) {
$('#shaddowimages img').each(function() {
$(this).attr('src', $(this).attr('src').replace('b_', 's_'));
});
count = 1;
} else {
$('#shaddowimages img').each(function() {
$(this).attr('src', $(this).attr('src').replace('s_', 'b_'));
});
count = 0;
}
})
});
我可以手动检查并替换每个 src,但是有 20+ 张图像,如果可以的话,我想要一种方法来自动化它。有什么帮助吗?
use .attr(
attributeName, function(index, attr) )
$('#shaddowimages img').attr('src', function (i, old) {
return old.replace('b_', 's_');
});
或最好使用 .prop( propertyName, function(index, oldPropertyValue) )
$('#shaddowimages img').prop('src', function (i, old) {
return old.replace('b_', 's_');
});
Read .prop() vs .attr()
可以在attr
内运行所有逻辑,因此您不必在'if
中复制代码
$('#changethumb').click(function() {
$('#shaddowimages img').attr('src', function (i, src) {
var newSrc= count==1 ? src.replace('b_', 's_') : src.replace('s_', 'b_');
count= count == 1 ? 10 : 1;
return newSrc;
});
});
似乎很奇怪,count
只有 1 或 10。复制了您的代码,但没有意义
相关文章:
- jQuery字符串使用split()方法在空格后拆分字符串
- jquery字符串变量上的每个函数
- 如何用javascript替换Jquery字符串上的新参数
- jQuery 字符串转义 onclick='deleteRow(item“+count+”)' 如何引用项目和计数
- 使jQuery字符串加载gettext
- 通过AJAX发送jquery字符串,并使用PHP将其保存到html文件中
- JS/Jquery:字符串到单词的文本分割脚本使用字典和最长匹配
- jQuery |字符串替换不起作用
- Jquery 字符串替换,只替换数组的开头
- 以下jQuery字符串连接代码有什么问题
- 未捕获的语法错误:jQuery 字符串中意外的标记 ILLEGAL
- 内联 jquery 字符串 - 为某些单词添加粗体字体
- jquery字符串到数字回到字符串
- jQuery 字符串解析日志 a 404
- JQuery 字符串“随机发生器”聚类字符
- Jquery 字符串连接
- jQuery字符串比较
- 是否可以在一个jquery字符串中使用两种颜色的字体
- Jquery字符串与正则表达式匹配不起作用
- jQuery字符串替换匹配的正则表达式