简体   繁体   中英

Json Individual Links in Table column

I have one page with a json table pulling in information from the json api. This works fine. Now my issue is, On the far right column i'm wanting a link to another page of mine, This link will be a unique link. At the moment, As you can see by the code, i can get it to link to the html page 12345, But all the rows link through to this. Which does not help Ha!

I'm ideally wanting the first button to link to 1.html then second button to link to 2.html and so on and so forth.

Here is the code i have so far.

          for(var i =0;i < json.results.collection1.length;i++) {

             var title = json.results.collection1[i].Name.text;

             var venue = json.results.collection1[i].Venue.text;
             var date = json.results.collection2[i].Date;
             var button = "<button class='redirect-button' data-url='12345.html'>Link</button>";



             $("#apple").append("<tbody><tr><td>"+title+"</td><td>"+venue+"</td><td>"+date+"</td><td>"+button+"</td></tr></tbody>");
           $("#apple").find(".redirect-button").click(function(){
   location.href = $(this).attr("data-url");
            });
           }

     },

Obviously all help would be greatly appreciated. Thanks Sam

Just to explain the comment above

The link you're creating is a <button> but really it's just a string. So by concatenating the URL part of the string based on something (like your i index in your loop) you can change it to anything you want. so for example :

var button = "<button class='redirect-button' data-url='" + i + " .html'>Link</button>";

this gives an element that looks like :

<button  class='redirect-button' data-url='0.html'>Link</button>

would give you 0.html, 1.html, etc (change the data-url='" + i + " .html' to data-url='" + (i+1) + " .html' and you get 1.html, 2.html, 3.html...)

or if you can change the API to give you a proper link in the return you can make it a bit more readable with:

var button = "<button class='redirect-button' data-url='" + json.results.collection2[i].LinkUrl + " .html'>Link</button>";

results in :

 <button  class='redirect-button' data-url='abcd.html'>Link</button>

assuming the return is called LinkURL and it's value is 'abcd'

Finally you append this string to the $("#apple") element and then the click event is added that looks for the data-url value and changes the current browser location to that new value.

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