gpt4 book ai didi

javascript - 点击不更新计数

转载 作者:行者123 更新时间:2023-11-29 16:57:15 25 4
gpt4 key购买 nike

我有两个多选菜单,我试图在其中获取加载时每个多选中总共有多少个 child ,然后根据点击事件更新数字,该点击事件会从一个菜单推送到另一个菜单,反之亦然反之亦然。

加载部分工作正常。我得到了我期望的结果并且计数是准确的。

我遇到的问题是在点击事件触发后更新这两个计数。我的计数永远不会改变。

这是我的代码和 fiddle :

var activeUser = $('.activeUsers');
var eligibleUser = $('.eligibleUsers');
var availableUserCount = $("#availableUsers option").length;
var eligibleUserCount = $("#eligibleUsers option").length;

activeUser.html(availableUserCount);
eligibleUser.html(eligibleUserCount);

$('#availableUsers').click(function () {
return !$('#availableUsers option:selected').remove().appendTo('#eligibleUsers');
activeUser.length(function() {
return availableUserCount();
});

eligibleUser.length(function() {
return eligibleUserCount();
});
});

$('#eligibleUsers').click(function () {
return !$('#eligibleUsers option:selected').remove().appendTo('#availableUsers');
activeUser.length(function() {
return availableUserCount();
});

eligibleUser.length(function() {
return eligibleUserCount();
});
});

http://jsfiddle.net/mujaji/8gkLyfe3/3/

我做错了什么?

最佳答案

您的代码似乎有 3 个问题。

  • 您在点击事件的第一行使用了return。所以下面的代码将永远不会被执行(摆脱它,只有当你找不到任何选项时才返回)
  • div 元素没有名为length 的方法。 (改用 .text())
  • 当您在函数 return availableUserCount(); 中返回长度时,它将返回缓存值。 (您需要再次重新选择该元素)

所以你的代码在技术上应该看起来像这样(仍然可以进行进一步的重构)

var activeUser = $('.activeUsers');
var eligibleUser = $('.eligibleUsers');
var availableUserCount = $("#availableUsers option").length;
var eligibleUserCount = $("#eligibleUsers option").length;

activeUser.html(availableUserCount);
eligibleUser.html(eligibleUserCount);

$('#availableUsers').click(function () {
!$('#availableUsers option:selected').remove().appendTo('#eligibleUsers');
activeUser.text(function() {
return $("#availableUsers option").length;
});

eligibleUser.text(function() {
return $("#eligibleUsers option").length;
});

});

$('#eligibleUsers').click(function () {
!$('#eligibleUsers option:selected').remove().appendTo('#availableUsers');
activeUser.text(function() {
return $("#availableUsers option").length;
});

eligibleUser.text(function() {
return $("#eligibleUsers option").length;
});
});

Check Fiddle

关于javascript - 点击不更新计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31326283/

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