草庐IT

javascript - 仅当 div 具有类 `is-active` 时才向输入添加文本

coder 2023-08-11 原文

问题

  • 未被选中的球员,即。没有 picked.is-active 的类在单击时不应添加到任何输入字段
  • 从每个类别中选出的球员数量上限为 4 名守门员中的 2 名、15 名防守队员中的 6 名球员和 31 名前锋中的 12 名球员。

更新#3

在此处添加指向 Github 存储库的链接:https://github.com/onlyandrewn/wheatkings

更新 #2

添加了片段,显示了如何切换 is-inactiveis-active 类。

更新 #1 -

我删除了第二个片段,它可能会引起一些困惑

下面的这个 Javascript 代码片段获取被点击的玩家的名字,然后将其放入输入字段,如果它有一个类 picked.is-active。但是,假设您已经选择了两个守门员,然后在未选择时单击该类别中剩余的两个守门员(默认类别 in-active)那些未选择的球员仍然会添加到输入中,这不是我们想要的。


scripts.js - 此代码段需要修复,目前将玩家名称添加到输入字段,即使已达到特定类别的最大玩家数

$(".player").on("click", function(){
    var playerNames = [];
    $("input:text").each(function(i, t) { playerNames.push(t.value) });

    if ($(this).find("picked.is-active")) {
        var playerName = $(this).find(".player__name").html();
        var index = playerNames.indexOf(playerName);

        if(index == -1) // add player
            $("input:text:eq(" + playerNames.indexOf("") + ")").val(playerName);
        else // remove player
            $("input:text:eq(" + index + ")").val("");
    } else {
        $("input").val("");
    }
});

scripts.js(如何切换 is-inactiveis-active 类)

$(".btn--random").on("click", function() {

    // CHECK THESE NUMBERS
    var goalies_array = getRandomNumbers(1, 4, 2);
    var defensemen_array = getRandomNumbers(5, 19, 6);
    var forwards_array = getRandomNumbers(20, 50, 12);

    $(".goalies").text(goalies_array.join(","));
    $(".defensemen").text(defensemen_array.join(","));
    $(".forwards").text(forwards_array.join(","));

    var players_array = goalies_array.concat(defensemen_array).concat(forwards_array);

    // Add the class `is-active` based on the numbers generated
    var player = $(".player");
    $(".is-active").removeClass("is-active").addClass("is-inactive");


    $.each(players_array, function(index, value) {
      var player_index = value - 1; // Subtract one based on zero-indexing
      player.eq(player_index).find(".is-inactive").removeClass("is-inactive").addClass("is-active");
  });
});

function getRandomNumbers(start, end, howMany) {
    var arr = [];
    for (var i = start, j = 0; i <= end; j++, i++)
        arr[j] = i
    arr.sort(function() {
        return Math.floor((Math.random() * 3) - 1)
    });

    return arr.splice(0, howMany)
}

index.html(表单片段)

    <form id="form">
        <input type="text" name="p1"  id="p1">
        <input type="text" name="p2"  id="p2">
        <input type="text" name="p3"  id="p3">
        <input type="text" name="p4"  id="p4">
        <input type="text" name="p5"  id="p5">
        <input type="text" name="p6"  id="p6">
        <input type="text" name="p7"  id="p7">
        <input type="text" name="p8"  id="p8">
        <input type="text" name="p9"  id="p9">
        <input type="text" name="p10" id="p10">
        <input type="text" name="p11" id="p11">
        <input type="text" name="p12" id="p12">
        <input type="text" name="p13" id="p13">
        <input type="text" name="p14" id="p14">
        <input type="text" name="p15" id="p15">
        <input type="text" name="p16" id="p16">
        <input type="text" name="p17" id="p17">
        <input type="text" name="p18" id="p18">
        <input type="text" name="p19" id="p19">
        <input type="text" name="p20" id="p20">

        <button class="btn btn--submit" type="submit"><img src="src/img/ballot-alt.png" class="image--ballot">Submit Vote</button>
    </form>

index.html(播放器片段)

        <div class="player player--forward year--2000 year--2010">
            <div class="tooltip">
                <p class="tooltip__name">Mark Stone</p>
                <p class="tooltip__hometown"><span>Hometown:</span> Winnipeg, Man.</p>
                <p class="tooltip__years"><span>Years Played:</span> 2008-2012</p>
                <div class="tooltip__stats--inline">

                    <div class="stats__group stats--games">
                        <p class="stats__header">GP</p>
                        <p class="stats__number stats__number--games">232</p>
                    </div>

                    <div class="stats__group stats--goals">
                        <p class="stats__header">G</p>
                        <p class="stats__number stats__number--goals">106</p>
                    </div>

                    <div class="stats__group stats--assists">
                        <p class="stats__header">A</p>
                        <p class="stats__number stats__number--assists">190</p>
                    </div>

                    <div class="stats__group stats--points">
                        <p class="stats__header">Pts</p>
                        <p class="stats__number stats__number--points">296</p>
                    </div>

                    <div class="stats__group stats--penalties">
                        <p class="stats__header">Pim</p>
                        <p class="stats__number stats__number--penalties">102</p>
                    </div>
                </div>
            </div>
            <div class="player__headshot player--mstone">
                <div class="picked is-inactive"><i class="fa fa-star" aria-hidden="true"></i></div>
            </div>
            <p class="player__name">Mark Stone</p>
            <p class="player__position">Forward</p>
        </div>

最佳答案

将应用状态存储到 dom/html 元素中并不是实现业务的好方法。您应该真正使用过数据对象来保存应用程序状态。然而,假设您的玩家名称是唯一的,以下将对每个类别强制执行最大计数限制。

(function () {
    var maxCounts = {
        forward: 12,
        defenceman: 6,
        goalie: 2
    };

    var getSelectePlayerNames = function () {
        var names = [];
        $("input:text").each(function (i, t) {
            t.value && names.push(t.value);
        });

        return names;
    };
    var getPlayerPositionCounts = function (players) {
        var $players = $('.player');
        var positions = [];
        $.each(players, function (i, player) {
            positions.push($players.find(".player__name:contains('" + player + "')").next().text().toLowerCase());
        });

        return positions.reduce(function (memo, val) {
            memo[val]++;
            return memo;
        }, { forward: 0, defenceman: 0, goalie: 0 });
    };

    $(".player").on("click", function () {
        var $el = $(this);

        var playerName = $el.find(".player__name").text();
        var selectedPlayerNames = getSelectePlayerNames();
        var index = selectedPlayerNames.indexOf(playerName);
        if (index > -1) {
            $("input:text:eq(" + index + ")").val("");

            return;
        }

        if (!$el.find(".picked.is-active").length) {
            return;
        }

        var playerPosition = $el.find(".player__position").text().toLowerCase();
        var selectedPositionCounts = getPlayerPositionCounts(selectedPlayerNames);
        if (selectedPositionCounts[playerPosition] < maxCounts[playerPosition]) {
            $("input:text:eq(" + selectedPlayerNames.length + ")").val(playerName);
        }
    });
})();

关于javascript - 仅当 div 具有类 `is-active` 时才向输入添加文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39196827/

有关javascript - 仅当 div 具有类 `is-active` 时才向输入添加文本的更多相关文章

  1. ruby - 具有身份验证的私有(private) Ruby Gem 服务器 - 2

    我想安装一个带有一些身份验证的私有(private)Rubygem服务器。我希望能够使用公共(public)Ubuntu服务器托管内部gem。我读到了http://docs.rubygems.org/read/chapter/18.但是那个没有身份验证-如我所见。然后我读到了https://github.com/cwninja/geminabox.但是当我使用基本身份验证(他们在他们的Wiki中有)时,它会提示从我的服务器获取源。所以。如何制作带有身份验证的私有(private)Rubygem服务器?这是不可能的吗?谢谢。编辑:Geminabox问题。我尝试“捆绑”以安装新的gem..

  2. ruby - 使用 ruby​​ 将 HTML 转换为纯文本并维护结构/格式 - 2

    我想将html转换为纯文本。不过,我不想只删除标签,我想智能地保留尽可能多的格式。为插入换行符标签,检测段落并格式化它们等。输入非常简单,通常是格式良好的html(不是整个文档,只是一堆内容,通常没有anchor或图像)。我可以将几个正则表达式放在一起,让我达到80%,但我认为可能有一些现有的解决方案更智能。 最佳答案 首先,不要尝试为此使用正则表达式。很有可能你会想出一个脆弱/脆弱的解决方案,它会随着HTML的变化而崩溃,或者很难管理和维护。您可以使用Nokogiri快速解析HTML并提取文本:require'nokogiri'h

  3. ruby-on-rails - active_admin 目录中的常量警告重新声明 - 2

    我正在使用active_admin,我在Rails3应用程序的应用程序中有一个目录管理,其中包含模型和页面的声明。时不时地我也有一个类,当那个类有一个常量时,就像这样:classFooBAR="bar"end然后,我在每个必须在我的Rails应用程序中重新加载一些代码的请求中收到此警告:/Users/pupeno/helloworld/app/admin/billing.rb:12:warning:alreadyinitializedconstantBAR知道发生了什么以及如何避免这些警告吗? 最佳答案 在纯Ruby中:classA

  4. ruby-on-rails - Rails 中的 NoMethodError::MailersController#preview undefined method `activation_token=' for nil:NilClass - 2

    似乎无法为此找到有效的答案。我正在阅读Rails教程的第10章第10.1.2节,但似乎无法使邮件程序预览正常工作。我发现处理错误的所有答案都与教程的不同部分相关,我假设我犯的错误正盯着我的脸。我已经完成并将教程中的代码复制/粘贴到相关文件中,但到目前为止,我还看不出我输入的内容与教程中的内容有什么区别。到目前为止,建议是在函数定义中添加或删除参数user,但这并没有解决问题。触发错误的url是http://localhost:3000/rails/mailers/user_mailer/account_activation.http://localhost:3000/rails/mai

  5. ruby-on-rails - Rails 5 Active Record 记录无效错误 - 2

    我有两个Rails模型,即Invoice和Invoice_details。一个Invoice_details属于Invoice,一个Invoice有多个Invoice_details。我无法使用accepts_nested_attributes_forinInvoice通过Invoice模型保存Invoice_details。我收到以下错误:(0.2ms)BEGIN(0.2ms)ROLLBACKCompleted422UnprocessableEntityin25ms(ActiveRecord:4.0ms)ActiveRecord::RecordInvalid(Validationfa

  6. ruby-on-rails - Nokogiri:使用 XPath 搜索 <div> - 2

    我使用Nokogiri(Rubygem)css搜索寻找某些在我的html里面。看起来Nokogiri的css搜索不喜欢正则表达式。我想切换到Nokogiri的xpath搜索,因为这似乎支持搜索字符串中的正则表达式。如何在xpath搜索中实现下面提到的(伪)css搜索?require'rubygems'require'nokogiri'value=Nokogiri::HTML.parse(ABBlaCD3"HTML_END#my_blockisgivenmy_bl="1"#my_eqcorrespondstothisregexmy_eq="\/[0-9]+\/"#FIXMEThefoll

  7. ruby-on-rails - Rails 3.1 中具有相同形式的多个模型? - 2

    我正在使用Rails3.1并在一个论坛上工作。我有一个名为Topic的模型,每个模型都有许多Post。当用户创建新主题时,他们也应该创建第一个Post。但是,我不确定如何以相同的形式执行此操作。这是我的代码:classTopic:destroyaccepts_nested_attributes_for:postsvalidates_presence_of:titleendclassPost...但这似乎不起作用。有什么想法吗?谢谢! 最佳答案 @Pablo的回答似乎有你需要的一切。但更具体地说...首先改变你View中的这一行对此#

  8. spring.profiles.active和spring.profiles.include的使用及区别说明 - 2

    转自:spring.profiles.active和spring.profiles.include的使用及区别说明下文笔者讲述spring.profiles.active和spring.profiles.include的区别简介说明,如下所示我们都知道,在日常开发中,开发|测试|生产环境都拥有不同的配置信息如:jdbc地址、ip、端口等此时为了避免每次都修改全部信息,我们则可以采用以上的属性处理此类异常spring.profiles.active属性例:配置文件,可使用以下方式定义application-${profile}.properties开发环境配置文件:application-dev

  9. ruby - 导轨 4 : column reference "updated_at" is ambiguous with Postgres - 2

    我正在尝试使用“updated_at”字段的日期时间范围查询数据库。前端在JSON数组中发送查询:["2015-09-0100:00:00","2015-10-0223:00:00"]在RailsController中,我使用以下方法将两个字符串解析为DateTime:start_date=DateTime.parse(params[:date_range_arr][0])end_date=DateTime.parse(params[:date_range_arr][1])#...@events=@events.where('updated_atBETWEEN?AND?,start_d

  10. ruby - 具有两个参数的 block - 2

    我从用户Hirolau那里找到了这段代码:defsum_to_n?(a,n)a.combination(2).find{|x,y|x+y==n}enda=[1,2,3,4,5]sum_to_n?(a,9)#=>[4,5]sum_to_n?(a,11)#=>nil我如何知道何时可以将两个参数发送到预定义方法(如find)?我不清楚,因为有时它不起作用。这是重新定义的东西吗? 最佳答案 如果您查看Enumerable#find的文档,您会发现它只接受一个block参数。您可以将它发送两次的原因是因为Ruby可以方便地让您根据它的“并行赋

随机推荐