• JS函数定义
  • pjax 加载 shuoshuo(); 函数
  • 首页
  • 渗透
  • 折腾
  • 转载
  • 关于Me
  • 榜上有名
  • 文章存档
  • 友情链接

不妨看看这里

会员面板

Base64 Image

JS 定义函数与PJAX导致代码高亮失效问题

  • Mr.Wu
  • 2017-12-31
  • 0
主题用了PJAX加载动画,因为这个加载动画的原因,导致在pjax下代码高亮、图片放大、随语等JS失效,实在不懂JS,在朋友的帮助下,成功解决,做个笔记。
由于 pjax 的特性,导致许多 JS 在 pjax 下并没有重新加载,所以我们需要在 pjax 加载时重新加载需要加载的 JS 代码,也就需要定义函数或者变量。

JS函数定义

//shuoshuo
$(function(){
    $('.shuoshuo-item .gdbt').on('click',function (){
    var $this = $(this).parent();
    var $content = $this.find('.foldContent');
    $this.siblings().removeClass('is-selected').find('.foldContent').hide();
    $this.toggleClass('is-selected')
    
    if($this.data('content')){
        $content.toggle();
        return ;
    }
    var $loading = $('<span style="color: #f55;">loading...</span>').appendTo($this.find('h5'));
    var ajax_data = {
        action: "shuoshuo",
        s_id:$this.attr('data-id')
    };
    $.post('/wp-admin/admin-ajax.php',ajax_data,function(res){
        $this.data('content',res);
        $loading.remove();
        
        $content.html(res).show();
    })
})
})
如上方代码 $(function() 表示页面加载完毕运行 {} 中的代码,$(function(){} 是 $(document).ready(function() 的简写,相当于 window.onload = function(){} $ 是 jQuery 的缩写。 需要在 pjax 重新加载 shuoshuo JS ,那么需要给它定义一个变量或者函数来实现调用。于是我们可以这样写:
//shuoshuo
function shuoshuo() {
$(function(){
    $('.shuoshuo-item .gdbt').on('click',function (){
    var $this = $(this).parent();
    var $content = $this.find('.foldContent');
    $this.siblings().removeClass('is-selected').find('.foldContent').hide();
    $this.toggleClass('is-selected')
    
    if($this.data('content')){
        $content.toggle();
        return ;
    }
    var $loading = $('<span style="color: #f55;">loading...</span>').appendTo($this.find('h5'));
    var ajax_data = {
        action: "shuoshuo",
        s_id:$this.attr('data-id')
    };
    $.post('/wp-admin/admin-ajax.php',ajax_data,function(res){
        $this.data('content',res);
        $loading.remove();
        
        $content.html(res).show();
    })
})
})}
shuoshuo();
在代码块外围添加 function shuoshuo() { }然后在末尾添加 shuoshuo(); 重新调用。这样的话我们就给 shuoshuo 这块 JS 代码添加了一个名为 shuoshuo();的函数。

pjax 加载 shuoshuo(); 函数

function reload_func() {
    $(function() {
        dataAnimate();
        prettyPrint();
        shuoshuo();
        newindow();
        singleimg();
    });
}
将shuoshuo();添加到 pjax 加载的地方,具体地方需要根据 pjax 的代码而定, 我的添加在上方的代码处即可。 可以发现,我在其中添加了很多函数,因为在 pjax 下,网站不止 一处JS失效,因此我用同样的方法,给其他的失效的 JS 添加了函数并且在 pjax 重新加载。如 prettyPrint(); 就是代码高亮函数,这个函数很多代码高亮通用哦,并不用重新定义函数的。 做完上面这些步骤,pjax 下不加载 JS的问题就解决了,感谢朋友的帮助,让我对 JS 有了一些了解,本文记录的是我个人的理解,如果有什么不对的地方,欢迎提出指正。感谢。
© 2025 MrWu
Theme by Wing-child
  • {{ item.name }}
  • {{ item.name }}