简体   繁体   中英

.indexOf() and window.open

I am required to use indexOf() and window.open to produce a picture of:

  • my athletes name, and
  • their picture, and
  • a short bio.

I am having trouble getting my global variables to work.

When I click on one of the athlete's names in the table I get a new screen but it says undefined where the athlete's name should be displayed.

External JavaScript:

My Global Variables and my attempt at making the window.

function teamStats(id) {
  var myWin = window.open("","", "height=200, width=500");
  var q = athleteNames.indexOf(id);myWin.document.write(
    "<p><b>Name</b> -   " + athleteNames[q] + </p>");
}

var athleteNames = ["Michael Phelps","Nathan Adrian",
  "Cody Miller","Ryan Murphy","Simone Manuel","Kathleen Baker",
  "Dana Vollmer","Lilly King"];
var athleteIds = ["MP","NA","CM","RM","SM","KB","DV","LK"]; 

My HTML code

Just a sample of the bottom part of my code. I have the opening tags to the table, main, div, and script.

        <td id="LK" onclick="teamStats(id)">Lilly King</td>
        <td>19</td>
        <td>5'4"</td>
        <td>154</td>
        <td> 
          <span style="color:gold">Gold</span> Women's 4x100m medley <br>
          <span style="color:gold">Gold</span> Women's 100m backstroke <br>
        </td> 
      </tr> 
    </table>
  </main>
</div>
<script>
  teamStats();
</script>

1) You should reorganize your "database" - put all data in one variable.

2) Getting properties of object more faster then indexOf

Javascript

var athletes = {
    MP: { // <- property is ID of athlete in your "database"
        name: "Michael Phelps", // <- fileds of data about your athlete
        pic: "http://placehold.it/350x150",
        bio: "Info about Michael Phelps"
    },
    NA: {
        name: "Nathan Adrian",
        pic: "http://placehold.it/350x150",
        bio: "Info about Nathan Adrian"
    }
};
function teamStats(id) {
    var athlete = athletes(id);
    var myWin = window.open("","", "height=200, width=500");
    myWin.document.write("<p><b>Name</b> -   " + athlete.name + "</p>" +
        "<img src='" + athlete.pic + "' />" +
        "<p>" + athlete.bio + "</p>");
}

HTML

<span id="MP" onclick="teamStats(id)">Michael Phelps</span>
<span id="NA" onclick="teamStats(id)">Nathan Adrian</span>

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