使用PHP和JavaScript动态更改链接目的地

Dynamically change link destinations using PHP and JavaScript

本文关键字:链接 目的地 动态 PHP JavaScript 使用      更新时间:2023-09-26

在我的网站上,我有一系列互动程序,用户必须能够编辑/删除等等。通常,互动程序(链接到Facebook等其他网站)只会直接链接到他们标记的目的地,但我希望用户能够启用"删除模式",允许他们通过点击来删除互动程序。

这些瓦片对每个用户都是唯一的,并且是通过PHP从数据库中调用的。我已经在tile的代码中添加了一个脚本,该脚本应该允许根据JavaScript变量更改链接,但我觉得PHP在最初加载链接后不允许更改存在问题。

这是我的代码:

<script>
    var mode = 1;
    function setMode(a) {
        mode = a;
    }
</script>
<?php
    $uid = $_COOKIE["UID"];
    include '../config.php';
    if (empty($uid)) {header('Location: /error?error=7');};
    $tile_counter = 0;
    error_reporting(0);
    $mysqli = new mysqli($db_servername, $db_username, $db_password, $db_name);
    // check connection
    if ($mysqli->connect_errno) {
        die("Connect failed: ".$mysqli->connect_error);
    }
    $query = "SELECT * FROM tiles where uid='$uid'";
    $result = $mysqli->query($query);
    while($row = $result->fetch_array()){
        if ($tile_trans == 1) {
            $tileColour = "rgba(0, 0, 0, 0.3)";
        }else{
            $tileColour = $row[colour];
        }
    //echo '<div class="tile" style="background-color:'.$tileColour.';width:'.$row[width].'px;"><img class="tileimg" src="http://'.$row[img_url].'"></div>';
    echo '
    <a id="'.$row[id].'" href="">
        <div class="tile hvr-reveal" id="tile" style="background-color:'.$tileColour.';width:'.$row[width].'px;">
            <img class="tileimg" src="http://'.$row[img_url].'">
        </div>
    </a>
    <script>
        if (mode == 1){document.getElementById("'.$row[id].'").setAttribute("href", "http://'.$row[link_url].'")}
        else if (mode == 2){document.getElementById("'.$row[id].'").setAttribute("href", "/php/tile/delete.php?id='.$row[id].'")}
    </script>';
    }
    ?>

用户可以访问几个按钮来更改上面显示的"模式"变量,它们看起来像这样:

<button onclick="setMode(2);">Delete</button></a>

如果我最初将"mode"变量设置为2,链接会正确更改,但在加载完所有内容后调用函数时,我无法更改链接。

此代码:

if (mode == 1){document.getElementById("'.$row[id].'").setAttribute("href", "http://'.$row[link_url].'")}
    else if (mode == 2){document.getElementById("'.$row[id].'").setAttribute("href", "/php/tile/delete.php?id='.$row[id].'")}

将只在加载页面时运行一次。您应该将其封装在一个函数中,该函数可以在用户触发setMode函数时调用。

function updateLinks()
  {
    if (mode == 1){document.getElementById("'.$row[id].'").setAttribute("href", "http://'.$row[link_url].'")}
    else if (mode == 2){document.getElementById("'.$row[id].'").setAttribute("href", "/php/tile/delete.php?id='.$row[id].'")}
  }

然后

function() setMode(mode) {
  ... whatever is already happening
  updateLinks()
}

您将遇到的问题是,您不能在PHP while中多次定义该函数。您需要将其移动到while之外,并找到不同的方法来引用正确的链接。