.indexOf()和window.open

时间:2016-11-12 21:24:58

标签: javascript html

我需要使用indexOf()window.open来生成以下图片:

  • 我的运动员姓名,
  • 他们的照片,
  • 一个简短的生物。

我无法让全局变量发挥作用。

当我点击表格中的一个运动员名字时,我得到一个新的屏幕,但它显示undefined应该显示运动员的名字。

外部JavaScript:

我的全局变量和我尝试制作窗口。

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"]; 

我的HTML代码

只是我代码底部的一个示例。我有表,main,div和脚本的开始标记。

        <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 个答案:

答案 0 :(得分:1)

1)您应该重新组织“数据库” - 将所有数据放在一个变量中。

2)获得对象的属性比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>