在 PHP 循环中调用 js 函数,同时将 php 变量作为参数传递给其中一个函数
Call js functions inside PHP loops while passing php variable as parameter to one of the functions
好的,所以创建了两个javascipt函数,我想在php循环中调用它们,同时将php变量作为参数传递给第二个函数
addElements($filePath)
这个 filePath 变量必须是内部循环中的最后一个,我想这样写不会从第一个循环中获取第一个变量
这是我想要的以及到目前为止所写的内容:
<script>
<?php foreach( glob( 'posts/*' ) as $filePath ){
//createPost(); call js function declared in header
foreach( glob( $filePath.'/*' ) as $filePath ){
//addElements($filePath) call second hs function declared in header here i pass the last $filePath from the second loop as parameter
}
}?>
</script>
再次尝试但仍然不起作用
<script>
<?php foreach( glob( 'posts/*' ) as $filePath ){
//createPost(); call js function declared in header
echo 'createPost()';
foreach( glob( $filePath.'/*' ) as $filePath ){
//addElements($filePath) call second hs function declared in header here i pass the last $filePath from the second loop as parameter
echo 'addElements('.$filePath.')';
}
}?>
PHP
仅在服务器端执行,因此您不能拥有执行 JavaScript 函数的 PHP 循环(javascript = 客户端)。但是,您可以在服务器上生成javascript代码,它将在客户端执行。
所以简单的解决方案是写这样的东西:
<script>
<?php
foreach( glob( 'posts/*' ) as $filePath ){
echo 'createPost();'; // call js function declared in header
foreach( glob( $filePath.'/*' ) as $filePath ){
echo 'addElements("'.$filePath.'");'; // call second hs function declared in header here i pass the last $filePath from the second loop as parameter
}
}
?>
</script>
它将生成类似这样的东西:
createPost();
addElements('filepathA');
addElements('filepathB');
addElements('filepathC');
createPost();
addElements('filepathD');
addElements('filepathE');
// ...
如您所见,这里没有循环。另一种解决方案是在服务器端创建一个数据数组,并使用 php 函数json_encode
php 函数来获得可以在客户端使用的 javascript 数据:
<?php
$results = [];
foreach( glob( 'posts/*' ) as $filePath ){
$subDirs = [];
foreach( glob( $filePath.'/*' ) as $filePath ){
$subDirs[] = $filePath;
}
$results[] = [
'dir' => $filePath,
'subDirs' => $subDirs
];
}
echo 'var data = ' . json_encode($results) . ';';
?>
你现在有一个可以像往常一样使用的javascript数组:
for (var i = 0; i < data.length; i++){
createPost();
for (var j = 0; j < data[i].subDirs.length; j++){
addElements(data[i].subDirs[j]);
}
}
相关文章:
- 在构造控制器、服务等时作为函数参数传递之前列出的角度 JS 变量
- 作为函数参数传递的匿名函数的范围
- 通过函数参数传递id
- 将数组值作为函数参数传递
- 是否需要初始化在 Javascript 中作为“类”构造函数参数传递的变量
- JavaScript 函数参数传递数组
- Angular2 将函数参数传递给构造函数
- 为什么我不能将角度变量作为函数参数传递
- jQuery - 基于作为函数参数传递的对象构建动态 if 语句
- 停止对作为函数参数传递到新列表的对象引用
- 在 JavaScript 中将数组作为内置函数参数传递
- AngularJS将范围变量名称作为函数参数传递
- Javascript 将对象作为函数参数传递
- 在对象上调用方法或将对象作为函数参数传递的差异
- 正确的方法:始终将所有变量作为函数参数传递
- 如何将动态创建的复选框值作为函数参数传递
- 节点简斯 |将对象作为函数参数传递
- 什么是将对象属性作为函数参数传递的良好策略/模式
- 将对象作为函数参数传递.不确定如何访问这些值
- 为什么我们要将函数参数传递到$scope$申请