如何在jQuery中使用php函数?
问题描述:
我的代码,我可以通过点击更改我的文字:如何在jQuery中使用php函数?
$('.SeeMore').click(function(){
\t \t var $this = $(this);
\t \t $this.toggleClass('SeeMore');
\t \t if($this.hasClass('SeeMore')){
\t \t \t $this.text('+ more'); \t \t \t
\t \t } else {
\t \t \t $this.text('- less');
\t \t }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<li class="SeeMore" style="cursor:pointer">+ more</li>
这是工作好为止。但是,因为我有我的页面的不同语言版本我想用PHP交流的话:
<script>
$('.SeeMore').click(function(){
var more = <?php echo $lang['MORE']; ?>
var less = <?php echo $lang['LESS']; ?>
var $this = $(this);
$this.toggleClass('SeeMore');
if($this.hasClass('SeeMore')){
$this.text(more);
} else {
$this.text(less);
}
});</script>
不幸的是现在我的代码不工作了,我不知道为什么。
答
有由你 -
1. Semi-colon at the end of the statement.
2. Double/single quotation around the PHP statement inside the jQuery.
您需要使用"
,防爆错过了两件事情:var more = "<?php echo $lang['MORE']; ?>";
答
你忘了分号和报价:
var more = "<?php echo $lang['MORE']; ?>";
var less = "<?php echo $lang['LESS']; ?>";
编写代码生成代码是硬而容易造成混淆。更好地使用体面的模板系统(例如Smarty)。
答
你就忘记了引号:
var more = "<?php echo $lang['MORE']; ?>";
var less = "<?php echo $lang['LESS']; ?>";
答
使用数据属性
HTML:
<li class="SeeMore" data-less="<?php echo $lang['LESS']; ?>" data-more="<?php echo $lang['MORE']; ?>" style="cursor:pointer">+ more</li>
JS:
$('.SeeMore').click(function(){
var more = $(this).attr('data-more');
var less = $(this).attr('data-less');
var $this = $(this);
$this.toggleClass('SeeMore');
if($this.hasClass('SeeMore')){
$this.text(more);
} else {
$this.text(less);
}
});
PS:不要忘记你包裹在一个文档准备声明
你需要使用'“',防爆单击事件:' var more =“
尝试呼应整个
@deviantxdes,该OP需要使用PHP里面的jQuery ... –