在PHP echo语句中的html标签的javascript中的双引号,单引号问题

时间:2013-05-11 15:30:50

标签: php javascript html

我正在使用echo语句和select tag的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;
}

所以我有什么方法可以使用这个功能

5 个答案:

答案 0 :(得分: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(或其他任何内容)。 这将使您免于接下来不可避免的引用不匹配问题。

答案 1 :(得分: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>');

答案 2 :(得分: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>');

答案 3 :(得分:0)

你可以逃避这样的单引号:

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

答案 4 :(得分: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>');