[英]How to access a php variable into external .js(my.js) file
How can I gain access to a PHP variable from an external javascript (my.js) file? 如何从外部javascript(my.js)文件获取对PHP变量的访问? I want to get the dynamic id or class into external js file
我想将动态ID或类添加到外部js文件中
PHP 的PHP
<div id="tabs<?php echo str_replace(' ', '',$child1['id']); ?>" class="<?php echo $activetab1; ?> tab-pane">
<?php if ($child1['children1']) { $category2=$child1['children1']; ?>
<ul class="tabs<?php echo str_replace(' ', '',$child1['id']); ?>" id="tabs<?php echo str_replace(' ', '',$child1['id']); ?>" data-count="15">
<?php foreach ($category2 as $child2) { ?>
<li>
<?php echo $child2['name']."------------main"; ?>
</li>
<?php if ($child2['children9']) { $category9=$child2['children9']; ?>
<?php foreach ($category9 as $child9) { ?>
<li>
<?php echo $child9['name']; ?>
<?php echo str_replace(' ', '',$child1['id']); ?>
</li>
<?php } } ?>
<?php } ?>
</ul>
<?php } ?>
</div>
External JavaScript 外部JavaScript
var container = $("ul.tabs25"),
count = container.data("count"),
column;
container.children().each(function(index) {
if (index % count == 0)
column = $("<li/>").css({"float": "left", "margin-right": "50px"}).appendTo(container);
var hello=$(this).appendTo(column);
console.log(hello);
});
I want to dynamically change this $child1['id']
within JavaScript. 我想在JavaScript中动态更改此
$child1['id']
。
You can access data from php script in Javascript (I'll use jQuery here) like this 您可以像这样从Javascript中的php脚本访问数据(我将在此处使用jQuery)
Create input hidden field within you php file like this 在您的php文件中创建输入隐藏字段,如下所示
<input type="hidden" id="myPhpValue" value="<?php echo $myPhpValue ?>" />
in your javascript file:
var myPhpValue = $("#myPhpValue").val();
//From here you can the whaterver you like with you js Value
if(myPhpValue != ''){
//Do something here
}
This will do the job 这样就可以了
A simple way to do this is to create an inline script with PHP. 一种简单的方法是使用PHP创建内联脚本。 Something like:
就像是:
<script type="text/javascript">
var myid=<?php echo str_replace(' ', '',$child1['id']); ?>;
</script>
This way myid is included in the html output of PHP. 这种方式myid包含在PHP的html输出中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.