gpt4 book ai didi

javascript - Wordpress 后端 Javascript 错误

转载 作者:行者123 更新时间:2023-11-30 16:18:36 26 4
gpt4 key购买 nike

我在 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');
});

控制台错误

语法错误,无法识别的表达式:li。 load-scripts.php?c=0&load[]=jquery-core,jquery-migrate,utils&ver=4.4.1:2

(9 个错误)无法读取未定义的 load-scripts.php 的属性“hasClass”?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');
});

正如我所提到的,遍历页面上一个类型的所有元素通常不是一个好主意。循环遍历具有给定类的一组元素会更好。

关于javascript - Wordpress 后端 Javascript 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35105990/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com