Wordpress 后端 Javascript 错误

Wordpress Back-end Javascript Error

本文关键字:错误 Javascript 后端 Wordpress      更新时间:2023-09-26

我在wordpress后端创建了一个自定义管理页面,并具有这个基本的html结构,

<ul data-status="available">
    <li class="available">AVAILABLE</li>
    <li class="onleave">ONLEAVE</li>
</ul>

当我在下面使用js代码时,它工作正常

$('ul').each( function() {
    var status = 'available';
    $(this).find('li.' + status ).addClass('active');
});

虽然下面的代码也可以工作(它在元素上添加了类),但是它会产生错误

$('ul').each( function() {
    var status = $(this).data('status');
    $(this).find('li.' + status ).addClass('active');
});

控制台上的错误

Syntax error, unrecognized expression: li. load-scripts.php?c=0&load[]=jquery-core,jquery-migrate,utils&ver=4.4.1:2

(9 Errors) Cannot read property 'hasClass' of undefined load-scripts.php?c=0&load[]=hoverIntent,common,admin-bar,svg-painter,heartbeat,wp-auth-check,thickb…:246

任何明确的解释将不胜感激

完整的JS代码

( function($) {
    'use strict';
    $(document).ready( function() {
        $('ul').each( function() {
            var status = $(this).attr('name');
            //$(this).find('li.' + status ).addClass('active');
        });      
        $('form').on('click', 'li', function() {
            var currentStatus = $(this).parent().attr('name');
            var id = $(this).parent().attr('id');
            var status = $(this).attr('name');
            var input = '<input id="model-'+id+'" type="hidden" name="'+id+'" value="'+status+'" />'
            if( currentStatus !== status || !currentStatus ) {
                $('form').prepend( input );
            } else {
                $('form').find('#model-'+id).remove();
            } 
            $(this).parent().find('li').removeClass('active');
            $(this).addClass('active');
        });
        $('form').submit( function(e) { 
            e.preventDefault();
            console.log( $( this ).serialize() );
        });
    });
})(jQuery);

一个快速(虽然不是很好的解决方案)是检查状态的值/类型,如果未定义,则跳出.each()循环:

$('ul').each( function() {
    var status = $(this).attr('name');
    if (typeof status === "undefined" || !status) {
        return false;
    };
    $(this).find('li.' + status ).addClass('active');
});

正如我提到的,在页面上循环遍历某个类型的所有元素通常是一个坏主意。最好使用给定类遍历一组元素。

试试这个:

$('ul').each( function() {
    var status = $(this).attr('data-status'); //note: data-status, not status
    $(this).find('li.' + status ).addClass('active');
});

.data() 方法用于设置/获取未在 Dom 中直观表示的对象级数据。但是,您正在使用属性,它在jQuery(.attr())中具有不同的访问器。

看这里:https://api.jquery.com/data/和这里http://api.jquery.com/attr/