我已经用PHP和JS编码了一段时间,但我却不经常这样做,所以我被一些应该很简单的东西所困扰,但这很适合我。我在这里找到的答案都没有解决问题。
当图像文件夹中存在多个名为[pagename] 1,2,3 ... png的图像时,我将JS幻灯片代码插入了WordPress页面。我一直在努力获取读取文件夹的代码,现在可以了。但是JS幻灯片无法在“菜单”页面上运行,而完全相同的代码却在“主页”页面上运行。两者之间的唯一区别是菜单代码会测试图像文件夹中是否存在图像。 (他们是。)
我确定代码的第一部分是正确的。第二段代码是问题所在。为什么JS无法开始幻灯片播放?这应该。代码在页面上正确读取。
<?php
$uploads = wp_upload_dir();
$x = 1;
$poname = $post->post_name;
if ($dir = opendir('/home/rowlandwilliams/public_html/lepeep/wp-content/themes/twentythirteen-child/images')) {
$images = array();
while (false !== ($file = readdir($dir))) {
if ($file != "." && $file != "..") {
$images[] = $file;
asort($images);
}
}
closedir($dir);
}
我认为这是问题所在:
foreach($images as $image) {
$subimg = substr($image, 0, -5);
if ($subimg == $poname) {
if ($x == 1) {
echo "<script type='text/javascript'>
function cycleImages(container) {
var $active = container.find('.active');
var $next = ($active.next().length > 0) ? $active.next() : container.find('img:first');
$next.css('z-index',2);
$active.fadeOut(1500,function() {
$active.css('z-index',1).show().removeClass('active');
$next.css('z-index',3).addClass('active');
});
$(document).ready(function() {
setInterval(function(){cycleImages($('#page-cycler'))}, 2000);
})
}
</script>"; ?>
<div class="cycler" id="page-cycler">
<?php $actstat = 'class="active"'; ?>
<?php $x++; ?>
<?php } else { ?>
<?php $actstat = ''; ?>
<?php } ?>
<img <?php echo $actstat; ?> src="<?php bloginfo('stylesheet_directory'); ?>/images/<?php echo $image; ?>">
<?php } ?>
<?php } ?>
</div><!-- #page-cycler -->
http://rowlandwilliams.com/lepeep/menu/
最佳答案
这是您的问题所在:
echo "<script type='text/javascript'>
function cycleImages(container) {
var $active = container.find('.active');
var $next = ($active.next().length > 0) ? $active.next() : container.find('img:first');
$next.css('z-index',2);
$active.fadeOut(1500,function() {
$active.css('z-index',1).show().removeClass('active');
$next.css('z-index',3).addClass('active');
});
$(document).ready(function() {
setInterval(function(){cycleImages($('#page-cycler'))}, 2000);
})
}
</script>";
当您使用
"
回显时,php将解析所有$var
...因此,变量
$active
和$next
是从php回显的,它看起来好像没有在代码中的任何地方设置。解决方案是将变量名从$active
更改为active
或使用单引号'
而不是双引号"
关于javascript - 应该很简单(但事实并非如此):PHP中的Javascript片段,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28258989/