4

我正在使用 echo 语句和选择标记的 onchange 我使用过 javascript

    echo('<select name="type"  onchange="(return location.href='.?&amp;class=.'+this.value;)" id="manage_ads">
        <option value="ads">Paid To Click Ads</option>
        <option value="banner_ads">Banner Ad</option>
        <option value="featured_ads">Featured Text Ads</option>
        <option value="featured_link">Featured Link Ads</option>
    </select>');

它显示错误,因为 href=' 这里单引号与 echo 语句冲突。

但是如果我在另一个 javascript 页面中使用它,那么该函数将无法正常工作,因为它给出了 classundefined 错误

function check()
{
    return location.href='.?&amp;class=.'+this.value;
}

那么有什么方法可以使用这个功能吗

4

5 回答 5

1

这些通常是跳入和跳出 PHP 模式的完美场景:

?>
<select name="type" onchange="(return location.href='.?&amp;class=.'+this.value;)" id="manage_ads">
    <option value="ads">Paid To Click Ads</option>
    <option value="banner_ads">Banner Ad</option>
    <option value="featured_ads">Featured Text Ads</option>
    <option value="featured_link">Featured Link Ads</option>
</select>
<?php

虽然不经常使用,但这种策略甚至可以在函数和方法的范围内实现:

function createSelectControl($name, array $options) {
    ?>
    <select name="<?= $name ?>">
        <?php 
            foreach ($options as $name => $value) {
                createSelectOption($name, $value);
            }
        ?>
    </select>
    <?php
}

function createSelectOption($name, $value) {
    ?>
        <option value="<?= $value ?>"><?= $name ?></option>
    <?php
}

重点是:不要使用 PHP 编写echo大量的 HTML(或任何与此相关的内容)。它将使您免于随后不可避免的报价不匹配问题。

于 2013-05-11T15:44:13.530 回答
0

你忘了逃离他们

echo('<select name="type"  onchange="(return location.href=\'.?&amp;class=.\'+this.value;)" id="manage_ads">
        <option value="ads">Paid To Click Ads</option>
        <option value="banner_ads">Banner Ad</option>
        <option value="featured_ads">Featured Text Ads</option>
        <option value="featured_link">Featured Link Ads</option>
    </select>');
于 2013-05-11T15:32:57.660 回答
0

试试这个,在 PHP 中你必须使用反斜杠转义单引号

echo('<select name="type"  onchange="(return location.href=\'?&amp;class=\'+this.value;)" id="manage_ads">

<option value="ads">Paid To Click Ads</option>
<option value="banner_ads">Banner Ad</option>
<option value="featured_ads">Featured Text Ads</option>
<option value="featured_link">Featured Link Ads</option>
</select>');
于 2013-05-11T15:33:25.690 回答
0

您可以像这样转义单引号:

echo('<select name="type"  onchange="(return location.href=\'.?&amp;class=.\'"+this.value;)"  ...
于 2013-05-11T15:33:31.257 回答
0

转义您希望在字符串中作为文字的单引号。像这样:

echo('<select name="type"  onchange="(return location.href=\'.?&amp;class=.\'+this.value;)" id="manage_ads">
            <option value="ads">Paid To Click Ads</option>
            <option value="banner_ads">Banner Ad</option>
            <option value="featured_ads">Featured Text Ads</option>
            <option value="featured_link">Featured Link Ads</option>
        </select>');
于 2013-05-11T15:34:25.370 回答