Javascript 用前面的结果定义变量,有更好的方法吗?
我正在编写一个网页,其中生成一个博客文章列表,以及相关数据(如时间戳和文章预览),并尝试为每一个博客文章生成一个唯一的变量,该变量递增一 为了做到这一点,我在第59行创建了一个名为“name”的变量,这将采用字符串“dtartnum”并将其与for循环的整数I(最大值为I)或变量$sqlindex(数据库中文章数的索引)连接起来 在第60行,我想用变量名的结果定义一个变量,并将$sqlindex的值赋给它(每次定义变量名的结果_时,它只是名称结果的占位符)。其原因(基于我读过的其他关于堆栈溢出的文章)是PHP只在页面加载期间执行(大致) 在这条逻辑线中,这意味着PHP变量将变得不可访问,并且必须在PHP生成页面时在本地以过程方式生成和存储 稍后,我计划使用我发现的AJAX库将变量发布到一个页面(该页面尚未创建),该页面将充当MySQL数据库中行的“id”(也是主键)(这样我就可以回忆该行以及该页面的相关信息)。在另一个页面上,我将有一个模板和一个填充空白MySQL查询,等待上面粘贴的页面中的行的“id” 通过查看堆栈溢出,我在Bash中发现了类似的东西,但是,由于语言在语法和功能上都非常不同,因此我在JS中找不到多少适用于此的应用程序。我找不到类似于JS的东西 总之,我的问题是: 如何用变量名的值定义“name”下的变量?i、 e.如果name=“土豆”;那么下面的变量将是potato=$sqlindex 而且,我猜是延伸的 有没有更好的办法?在结构上是否有可以改进的地方?请让我知道,这样我就可以用这个未来的项目 正在讨论的代码位于herdoc的底部,注释掉的块的上方 如果你需要我补充什么,请告诉我 守则:Javascript 用前面的结果定义变量,有更好的方法吗?,javascript,php,mysql,Javascript,Php,Mysql,我正在编写一个网页,其中生成一个博客文章列表,以及相关数据(如时间戳和文章预览),并尝试为每一个博客文章生成一个唯一的变量,该变量递增一 为了做到这一点,我在第59行创建了一个名为“name”的变量,这将采用字符串“dtartnum”并将其与for循环的整数I(最大值为I)或变量$sqlindex(数据库中文章数的索引)连接起来 在第60行,我想用变量名的结果定义一个变量,并将$sqlindex的值赋给它(每次定义变量名的结果_时,它只是名称结果的占位符)。其原因(基于我读过的其他关于堆栈溢出的
<?php
$conn = new mysqli($servername, $username, $password, $db);
//check Connection
if ($conn->connect_error){
die("ERROR: ". $conn->connect_error);
}
else{
//nothing, essentially
}
$rowcountsql= "SELECT id FROM writeups ORDER BY id;";
if ($result=$conn->query($rowcountsql))
{
// Return the number of rows in result set
$rowcount=mysqli_num_rows($result);
}
for ($sqlindex = 0; $sqlindex <= $rowcount; $sqlindex++){
if ($result = $conn->query("SELECT * FROM writeups LIMIT ".$sqlindex.", 1;")){
if ($count = $result->num_rows){
// echo "The row count for this query is ",$count,"<br>";
while($row = $result->fetch_object()){
$titlecontent = $row->title;
$writeupcontent = $row->body;
$rowdateandtime = $row->dateandtime;
$article_number = $sqlindex + 1;
echo $str=<<<ARTICLE
<div class="article">
<div class="titleanddate">
<h2>$titlecontent</h2>
<h3 class="dtartnum">Written $rowdateandtime, Article Number $article_number</h3>
</div>
<div class="truncate">
<p class="writeup">
$writeupcontent
</p>
<a href="templatepage.php" onmouseenter="assignCookie()">Read More...</a>
<script>
function assignCookie(){
//total nr in list
window.alert(document.getElementsByClassName("article").length);
//pos in list and definition of variable per button
for (i=0; i<=sqlindex;i++){
var name = "dtartnum"+i;
var result_of_name = $sqlindex;
window.alert(result_of_name);//how do we get this to work?
}
/* This code will be developed later, I suppose... need to fix the above first
window.alert(dtartnum);
var pattern = /Article Number \d{1,3}/;
if(pattern.test(document.getElementsByClassName(dtartnum).value)){
window.alert(pattern.test(document.getElementsByClassName(dtartnum).value));
}
else{
window.alert(getElementsByClassName(dtartnum).value);
}*/
}
</script>
</div>
</div>
ARTICLE;
}
}
}
}
?>
这应该可以
var name = "potato";
this[name] = $sqlindex;
alert(potato);
可能的重复似乎把我带向了正确的方向。让我重构一些代码,看看是否解决了这个问题。