-1

当我只输出一行时,我在将 php 输出到 javascript 时遇到问题 当我将我的 for 循环放入 javascript 时,javascript 工作正常,没有错误,只是没有输出我使用 firebug,我看到输出有问题,例如:

“'ANS”。'+' 。“回答”。'+' 。“'ANS” 如果我从 php 输出这样的文本,它可以工作。当我像这样输出一个锚点时:

'"' . '<a href="#">Text</a>' . '"';

但是,当我将其放入 for 循环时,它会中断,我尝试了许多选项:

function step1() {
            modalbox.show(new Element("div").insert(
                new Element("p", { "align": "justify" }).insert(
                    <?php $i = 0; ?>
                    <?php foreach ($items as $category => $itemsattr): $i++; ?>
                        <?php if($i == 27): ?>
                            <?= "'" . '<a class="category" href="#"> '. $category . '</a>' . "'" ?>
                        <?php endif; ?>
                            <?= "'" . '<a class="category" href="#"> '. $category . '</a>' . "'+" ?>
                    <?php endforeach; ?>
                )
            ), {
                "title"     : "Step 1/3",
                "width"     : 800,
                "options"   : [{
                    "label"     : "Next »",
                    "onClick"   : step2
                }]
            });
        };

如果我只输出这样的一个,它可以工作:

<?= "'" . '<a class="category" href="#">Text</a>' . "'" ?>

但是,当我把它放在一个循环中并在除最后一个之外的每个末尾添加 '+ 时,它会中断。

当使用 Firebug 检查时,我的 for 循环会输出:

'<a class="category" href="#"> Assault Ship</a>'+ '<a class="category" href="#"> Battlecruiser</a>'

据我所知,这应该对 javascript 有效,是否有另一种更安全的方式来输出 php 过去的 javascript 以避免这样的问题?

4

1 回答 1

1

Instead of this:

<?php foreach ($items as $category => $itemsattr): $i++; ?>
    <?php if($i == 27): ?>
        <?= "'" . '<a class="category" href="#"> '. $category . '</a>' . "'" ?>
    <?php endif; ?>
        <?= "'" . '<a class="category" href="#"> '. $category . '</a>' . "'+" ?>
<?php endforeach; ?>



What if you try something like this?

<?php echo "'"; ?>
<?php foreach ($items as $category => $itemsattr): $i++; ?>
    <?php if($i == 27): ?>
        <?= '<a class="category" href="#"> '. $category . '</a>' ?>
    <?php endif; ?>
        <?= '<a class="category" href="#"> '. $category . '</a>' ?>
<?php endforeach; ?>
<?php echo "'"; ?>



You also may have better luck with this; it's more scalable than what you had:

<?php foreach ($items as $category => $itemsattr): $i++; ?>
    <?php if($i == 0): ?>
        <?= "'" . '<a class="category" href="#"> '. $category . '</a>' . "'" ?>
    <?php else: ?>
        <?= "+'" . '<a class="category" href="#"> '. $category . '</a>' . "'" ?>
    <?php endif; ?>
<?php endforeach; ?>

Note the different placement of the + as well as the first conditional.

Like others have said, this general approach may not be the best, but this might make what you have work better...

于 2012-10-18T22:40:03.183 回答