[英]How can I use a checkbox to modify an HREF?
I am making an image gallery with a user preference checkbox that displays a large or jumbo size image when the thumbnail is clicked. 我正在制作一个带有用户首选项复选框的图像库,该复选框会在单击缩略图时显示大尺寸或超大尺寸的图像。 I have a form element on the page that looks like this: 我在页面上有一个如下所示的表单元素:
<input type="checkbox" name="targetbox" id="pref"
onclick="supersize(this.checked);">
<label for="pref">Supersize Pics</label>
I also have a link and thumbnail like this: 我也有这样的链接和缩略图:
<a href="images/large/image1.jpg"><img src="images/thumbs/image1.jpg" /></a>
The part that is giving me some trouble is the JavaScript. 给我带来麻烦的部分是JavaScript。 Here is what I was able to cobble together so far: 到目前为止,这是我能够完成的工作:
<script language="JavaScript">
function supersize(checkme) {
if (checkme)
where = "images/super/";
else
where = "images/large/";
for (var i=0; i<=(document.links.length-1); i++) {
document.links[i].href = where;
}
}
</script>
This will replace the links, but not how I need them. 这将替换链接,但不会替换我的需要方式。 Obviously, this will replace the entire href
, and I need to retain the "image1.jpg" so the new link would be something like: "images/super/image1.jpg". 显然,这将替换整个href
,并且我需要保留“ image1.jpg”,因此新链接将类似于:“ images / super / image1.jpg”。 I am sure I need to use an array or split the url into two parts or something. 我确定我需要使用数组或将网址分为两部分。 That's the part I am having trouble figuring out. 那就是我难以弄清的部分。 Any help would be appreciated. 任何帮助,将不胜感激。
I'd suggest using a simple replace()
: 我建议使用一个简单的replace()
:
var href = document.links[i].href;
if (href.indexOf('super') > -1){
document.links[i].href = href.replace('super','large');
}
else {
document.links[i].href = href.replace('large','super');
}
This will, of course, simply replace the large
string with the super
string, or vice versa. 当然,这将简单地用super
字符串替换large
字符串,反之亦然。 So, tailor your if
to suit. 因此,定制您if
适合。
References: 参考文献:
如果知道最后一个值,则可以使用replace()
:
document.links[i].href = document.links[i].href.replace("last/value/goes/here/", where);
Try this function. 试试这个功能。
hrefLink.lastIndexOf('/')+1 gets the position of the last "/" and .substr() fetches the image name, which can later be appended to whatever you want ! hrefLink.lastIndexOf('/')+ 1获取最后一个“ /”的位置,.substr()获取图像名称,该名称以后可以附加到任何您想要的名称上!
<script language="JavaScript">
function supersize(checkme) {
if (checkme)
where = "images/super/";
else
where = "images/large/";
for (var i=0; i<=(document.links.length-1); i++) {
hrefLink = document.links[i].href;
imgName = hrefLink.substr(hrefLink.lastIndexOf('/')+1);
document.links[i].href = where+imgName;
}
}
</script>
This way, we keep the function independent of the hard-coded words like "super" and "large" here in your context. 这样,在您的上下文中,我们使函数独立于诸如“ super”和“ large”之类的硬编码单词。
Cheers, Harsha. 干杯,哈莎。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.