【问题标题】:PHP - Dynamically change variablePHP - 动态改变变量
【发布时间】:2014-02-18 14:25:26
【问题描述】:

我的网站在具有动态 CSS 更改的单个页面上运行。如果我想将客户端定向到页面内容,我所做的就是提供带有 CSS id 的页面链接。即:www.ilstours.net/index.php?css=1

index.php:

    <!DOCTYPE html>
    <html>
    <head>
    <link rel="stylesheet" type="text/css" href="css/<?php echo $css; ?>.php" />
    </head>
    <body>
<button id="button1" type="button" onclick="index.php?css=2">Update</button> 'HERE
    </body>
    </html>

1.php:

<?php
header("Content-type: text/css; charset: UTF-8");
$Color = "black";
?>
body {background-color:<?php echo $Color ?>;}

2.php:

  <?php
    header("Content-type: text/css; charset: UTF-8");
    $Color = "red";
    ?>
    body {background-color:<?php echo $Color ?>;}

如何在按钮单击时切换到 CSS 文件 2.php?

【问题讨论】:

  • 当前代码有什么问题?您希望每次点击都更改您的网址?
  • onclick="index.php?css=2" 这不是一个有效的属性值。我想在 php 中操作变量。
  • @Litestone 你检查我的答案了吗?
  • 我建议你使用jQuery

标签: php html css


【解决方案1】:

index.php

<?php
$css = 1; // default css (1)
if(isset($_REQUEST['css']) && ($_REQUEST['css']==1 || $_REQUEST['css']==2))
{
  $css = $_REQUEST['css']; // update by click on button (1 or 2)
}

?>
      <!DOCTYPE html>
        <html>
        <head>
        <link rel="stylesheet" type="text/css" href="css/<?php echo $css; ?>.php" />
        </head>
        <body>
            <button id="button1" type="button" onclick="location.href='index.php?css=1';">Update CSS 1</button>
            <button id="button1" type="button" onclick="location.href='index.php?css=2';">Update CSS 2</button>

        </body>
        </html>

【讨论】:

  • 你写的是 $_REQEUST 而不是 $_REQUEST
【解决方案2】:

当你通过 url 传递值时,使用 $_GET 来访问它

<link rel="stylesheet" type="text/css" href="css/<?php echo $_GET['css']; ?>.php" />

【讨论】:

  • 我没想到 GET 变量。这是个好主意。但它仍然不能动态工作。
  • 您的 onclick 属性中还需要“location.href”。我认为@Satish Sharma 的答案是您所需要的
  • 它使用的是 $_REQUEST['css'] 而不是 $_GET['css']。有什么区别?
  • 一般$_REQUEST包含$_GET或$_POST的内容。当您从 url 请求数据时,您使用 $_GET。在您的情况下,$_GET 应该可以工作。尝试将@SatishSharma 代码与$_GET 一起使用。
  • 他的代码乍一看运行良好,但是,它破坏了所有过渡效果,如持续时间,因为location.href 就像导航到不同的链接一样。我仍在寻找替代方法。
【解决方案3】:
if(isset($_GET['css'])) {
    echo '<link rel="stylesheet" type="text/css" href="css/'.$_GET['css'].'.php" />';

}

【讨论】:

    【解决方案4】:

    最好将你的 css 保存在单个数组中,例如

    <?php
       $my_css = array("1"=>"1.css","2"=>"2.css",'deflt' => 'defualt.css');
    ?>
    

    并包含类似的css

    <link rel="stylesheet" type="text/css" href="css/<?php echo (isset($_GET['css']) && isset($my_css[$_GET['css']])) ? $my_css[$_GET['css']] : 'defualt.css'; ?>" />
    

    【讨论】:

    • 如果 url 是 index.php?css=abcd 将加载哪个 css
    猜你喜欢
    • 1970-01-01
    • 2023-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-15
    • 1970-01-01
    • 1970-01-01
    • 2015-08-18
    相关资源
    最近更新 更多