试图为for循环函数分配id

时间:2017-03-03 13:22:32

标签: javascript jquery

我要做的是在动态信息中添加一个ID。这一行

 var webaddress = '<img id= "[index]" src="http://pokeapi.co/media/img/[index].png">';

如果我取出id="[index]循环工作正常并给我图像。但我需要为所有人添加一个id,以便我可以做其他事情。如果有人可以告诉我如何更改docuent.write(文本)以写入specfice div,那么我可以将我的脚本放在页面顶部,这样可以获得帮助。

<!DOCTYPE html>
<html>

<head>
    <title></title>
    <meta charset="utf-8">
    <link rel="stylesheet" type="text/css" href="style.css">
    </style>
    <script type="text/javascript" rel="script" type="script" href="script.jss"></script>
    <script type="text/javascript" src='http://code.jquery.com/jquery-1.10.2.min.js'></script>
    <script type="text/javascript">
    $(document).ready(function() {



    });
    </script>
</head>

<body>
    <div id="wrapper">
    </div>
    <div id="pokedeck">
        <div id="pokelist">
            <script type="text/javascript">
            var webaddress = '<img id= "[index]" src="http://pokeapi.co/media/img/[index].png">';
            var text = "";
            for (var i = 1; i <= 152; i++) {
                text += webaddress.replace("[index]", i);
            }
            document.write(text);
            </script>
        </div>
        <div id="deck1"></div>
    </div>

1 个答案:

答案 0 :(得分:2)

方括号是特殊字符,因此您需要将它们转义。请参阅下面的代码(我已添加评论)

{
    "shell_cmd": /*"make"*/
}
// the following goes in your document ready

var webaddress = '<img id= "[index]" src="http://pokeapi.co/media/img/[index].png">';
var pokelist = $('#pokelist');               // get your pokelist

for (var i = 1; i <= 152; i++) {
  var image = webaddress.replace(/\[index\]/g, i);  // escape your square brackets and make it a global replace - anything inside the / / is replaced and the g means all occurences of
  pokelist.append(image);                           // append it to your div
}

我还会将你的脚本移到关闭的body标签之前,而不是将它们放在标题