我正在尝试加载基于浏览器视口的动态侧边栏。如何用 jQuery 变量替换图像路径的特定单词?
我的代码:
body>
<div id="wrapper">
<div id="aside"> </div>
<div id="content">
<h1>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</h1>
<p><img src="img/bar-0/sample.jpg">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum sit amet justo vel diam interdum posuere. <img src="img/bar-0/sample1.jpg">Aliquam erat volutpat. Nulla sed libero nunc. Cras in lacus in dolor feugiat scelerisque nec id nisi.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum sit amet justo vel diam interdum posuere. Aliquam erat volutpat. <img src="img/bar-0/sample2.jpg">Nulla sed libero nunc. Cras in lacus in dolor feugiat scelerisque nec id nisi.<img src="img/bar-0/sample2.jpg"></p>
</div>
</div>
<script type="text/javascript">
$(document).ready(function() {
var curwidth, script, prevclass;
function reloadBars(width) { var newclass
width = parseInt(width, 10);
newclass = ""
if (width < 801 && (curwidth == -1 || curwidth > 800)) {
newclass = 'bar-0';
bar = '800.php';
} else if ((width > 800 && width < 1201) && (curwidth < 800 || curwidth > 1201)) {
newclass = 'bar-1';
bar = '1000.php';
} else if ((width > 1200 && width < 1601) && (curwidth < 1200 || curwidth > 1601)) {
newclass = 'bar-2';
bar = '1200.php';
} else if (width > 1600 && curwidth < 1600) {
newclass = 'bar-3';
bar = '1600.php';
} else {
return;
}
$.ajax({
type: "POST",
url: bar,
data: {},
success:
function(response) {
$('#aside').html(response);
$('#aside').addClass(newclass);
$("#aside").removeClass(prevclass);
$("img").each(function() {
var src = $(this).attr('src');
src = src.replace(prevclass, newclass);
$(this).attr('src', src);
});
prevclass = newclass;
},
error: function(e) {
alert("UH OH! Error!");
}
});
curwidth = width;
}
prevclass = ""
curwidth = -1;
reloadBars($(this).width());
$(window).resize(function() {
reloadBars($(this).width());
});
});
</script>
</body>
在这里,我特别想用变量值替换bar-0
它出现的任何地方。我试图通过使用如上所示的代码来实现这一点:<img>
newclass
更新:它给出了一个错误:
"NetworkError: 404 Not Found - http://localhost/final/bar-1img/bar-0/sample1.jpg"
理想情况下,路径应该是http://localhost/final/img/bar-1/sample1.jpg
它应该替换bar-0
但它在img/
.