[英]Change href onclick with multiple variables
I know very little about js so please be gentle. 我对js知之甚少,所以请保持谦虚。
I'm using the below code which was originally used to swap classes. 我正在使用下面的代码,该代码最初是用来交换类的。 I thought it would be as simple as changing
.className
to .href
but I was wrong. 我以为那就像将
.className
更改为.href
一样简单,但是我错了。
My problem is that it works once and then stops. 我的问题是,它只能运行一次然后停止。
$(document).ready(function(){
$('#click').click(function () {
$('#url').each(function(){
var classes = ['/1','/2','/3','/4'];
this.href = classes[($.inArray(this.href, classes)+1)%classes.length];
});
});
});
EDIT: Here is the html I'm using: 编辑:这是我正在使用的html:
<a id="url" href="/0">hello</a>
My goal is to switch /0 with /1 then /2 and so on with each onclick. 我的目标是在每次onclick时将/ 1切换为/ 0,然后将/ 2切换为依此类推。
You can use .attr()
, set a varible to -1
. 您可以使用
.attr()
,将变量设置为-1
。 At click
event handler increment variable until variable reaches classes.length
, then reset variable to 0
, without utilizing Remainder
operator. click
事件处理程序时,将变量递增,直到变量达到classes.length
为止,然后将变量重置为0
,而不使用Remainder
运算符。
$(document).ready(function() { var classes = ['/1','/2','/3','/4']; var i = -1; var url = $("#url"); $('#click').click(function () { i = (++i < classes.length) ? i : 0; url.attr("href", classes[i]); console.log(url.attr("href")); }); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"> </script> <button id="click">click</button> <a id="url" href="/0">hello</a>
This fails because the protocol file://
or http://
is silently added the the href
value. 失败是因为协议
file://
或http://
被静默添加了href
值。
So change this: 所以改变这个:
$.inArray(this.href, classes)
to: 至:
$.inArray(this.href.replace(/^.*?\/\//, ''), classes)
... which removes the protocol from the string before looking it up in your array. ...会从字符串中删除协议,然后再在数组中查找协议。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.