![](/img/trans.png)
[英]Change the URL dynamically for “Add New Item” link using javascript/jquery
[英]Dynamically change link destinations using PHP and JavaScript
在我的网站上,我有一系列磁贴,用户必须能够编辑/删除等。通常,磁贴(与其他网站(如Facebook)的链接)将直接链接到其标记的目的地,但我希望用户能够启用“删除模式”,从而允许他们通过单击该图块来删除该图块。
这些磁贴对于每个用户都是唯一的,可以通过PHP从数据库中调用。 我已经在图块的代码中添加了一个脚本,该脚本应允许根据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>';
}
?>
用户可以访问几个按钮来更改上面显示的“ mode”变量,它们看起来像这样:
<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
然后找到另一种方式来引用正确的链接。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.