简体   繁体   中英

Change href onclick with multiple variables

I know very little about js so please be gentle.

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.

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:

<a id="url" href="/0">hello</a>

My goal is to switch /0 with /1 then /2 and so on with each onclick.

You can use .attr() , set a varible to -1 . At click event handler increment variable until variable reaches classes.length , then reset variable to 0 , without utilizing Remainder operator.

 $(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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM