Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/385.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 需要切换选定的div,并增加计数器_Javascript_Jquery_Html_Css - Fatal编程技术网

Javascript 需要切换选定的div,并增加计数器

Javascript 需要切换选定的div,并增加计数器,javascript,jquery,html,css,Javascript,Jquery,Html,Css,我需要允许用户点击一系列div。他们基本上是选择x个项目(每个项目在一个div中)添加到一个组中。每个项目只能添加一次。但他们也应该能够取消选择项目 每次选择一个项目时,它的id都会添加到表单字段中,这样我就可以捕获所有选定项目id的逗号分隔列表 只能选择x个项目。因此,我需要保持选中项目的运行计数,并停止选择其他项目的功能。当然,如果未选中所选项目,则计数将向下递增 我现在拥有的是,将正确的项目ID添加到表单字段,并在每次单击时正确地打开和关闭div样式。但是,它只是不断地将ID添加到表单字段

我需要允许用户点击一系列div。他们基本上是选择x个项目(每个项目在一个div中)添加到一个组中。每个项目只能添加一次。但他们也应该能够取消选择项目

每次选择一个项目时,它的id都会添加到表单字段中,这样我就可以捕获所有选定项目id的逗号分隔列表

只能选择x个项目。因此,我需要保持选中项目的运行计数,并停止选择其他项目的功能。当然,如果未选中所选项目,则计数将向下递增

我现在拥有的是,将正确的项目ID添加到表单字段,并在每次单击时正确地打开和关闭div样式。但是,它只是不断地将ID添加到表单字段中。“x”编号没有限制,并且在取消选择项目时不会删除ID

任何帮助都会很棒

以下是html:

    <h3 style="border-top:none;padding-top:0;">Choose <div id="boxQ">3</div> Items for Your Box</h3>
{% set featuredCollection = 'clctn-box-items'|collection %}
{% for product in featuredCollection.products %}
    <div class="row">
        <div class="twelve columns">
            <div class="box-items" id="tag{{ product.id }}" value="{{ product.id }}">
               {{ product.name }} <img class="box-item-thumb" align="right" src="{{ product.images.first.thumbnail('auto', 65)|default('http://placehold.it/100x65') }}"/>
            </div>
        </div>
    </div>
{% endfor %}
<input type="text" id="boxItemIDs" name="box_item_ids" value="">
以下是jquery:

//
// Set Selected Item Count - numer of items allowed for this box 
//
var itemCount;
$( function() {
    var urlString = window.location.href;
    var thesplit = urlString.substring(urlString.lastIndexOf("/")+1).split('-');
    itemCount = thesplit[0];

});
//
// Handle Box Item Clicks
//
var count = 0;
$( document ).ready(function() {

    document.getElementById("boxQ").innerHTML = itemCount;

    $('div[id^="tag"]').on('click', function() {  
        var $thisDiv = $( this );
        count++;
        $thisDiv.toggleClass( "itemClicked");
        var ids = $(this).attr('value');
        var resultObj = $("#boxItemIDs");
        var stringToAppend = resultObj.val().length > 0 ? resultObj.val() + "," : "";
        resultObj .val( stringToAppend + ids );


    });


});

这是我为它创建的一个提琴:它不起作用。

我无法用你的提琴页面测试它(因为把手(?)模板没有正确呈现),但是,通过一些重新排列、重命名变量和一些额外的操作,我尝试引导你走上正确的道路:

$('div[id^="tag"]').on('click', function() {  
    var $thisDiv = $( this );
    var resultObj = $("#boxItemIDs");
    var id = $thisDiv.attr('value'); 
    var selectedIds = resultObj.val().split(',');
    var idIndex = selectedIds.indexOf(id);

    // item is currently selected
    if (idIndex >= 0) {
        selectedIds.splice(idIndex, 1);
    }
    else {
        selectedIds.push(id);
    }
    count = selectedIds.length;

    $thisDiv.toggleClass( "itemClicked");
    resultObj.val( selectedIds.join(",") );
});

这是我对这个问题的看法。我的第一直觉是,这有点臃肿,如果我有更多的时间,可以瘦身,但希望这将把你在正确的方向。我还放了一把小提琴,这样你就可以玩它,看看所有的东西是如何一起工作的。我希望这有帮助

小提琴:


我认为这是实现你想要的最简单的方法:

JS:

Html:

点击我
点击我
点击我
点击我

小提琴:

你能做一把小提琴吗?请给我们最后一个客户端HTML。我还没有看到您的代码中定义的任何使用
计数的条件。我将为此使用小提琴。我上次试的时候没法让它运行。我再试一次。而且计数还没有被整合…更确切地说,我之前删除了我尝试过的b/c。它不起作用。只是为此创建了一个提琴,并在问题的底部添加了链接。哇,谢谢大家。齐夫和兰斯的解决方案都有效。我要用Ziv的b/c代码比较干净。谢谢大家!!好的,干净的方法。谢谢你,齐夫!
$('div[id^="tag"]').on('click', function() {  
    var $thisDiv = $( this );
    var resultObj = $("#boxItemIDs");
    var id = $thisDiv.attr('value'); 
    var selectedIds = resultObj.val().split(',');
    var idIndex = selectedIds.indexOf(id);

    // item is currently selected
    if (idIndex >= 0) {
        selectedIds.splice(idIndex, 1);
    }
    else {
        selectedIds.push(id);
    }
    count = selectedIds.length;

    $thisDiv.toggleClass( "itemClicked");
    resultObj.val( selectedIds.join(",") );
});
// Set Selected Item Count - arbitrary number for DEMO purposes
var itemCount = 3;
var count = 0;
var items= [];

document.getElementById("boxQ").innerHTML = itemCount;

$('div[id^="tag"]').on('click', function() {

    var $thisDiv = $( this );
    var ids = $(this).attr('value');
    var resultObj = $("#boxItemIDs");

    // If the row has been clicked already we need to remove it
    if ($thisDiv.hasClass("itemClicked")) 
    {
        $thisDiv.removeClass("itemClicked");

        var index = items.indexOf(ids);
        if (index > -1) {
            items.splice(index, 1);
        }
        resultObj.val(items.join(','));
        count--;  
    }
    else
    {
        // If count equals itemCount throw an error
        if (count === itemCount) 
        {
            console.log("Too many items in the box yo!");
            // This would be a great place to put an error message...
        }

        // Otherwise we need to continue and add it.
        else 
        {
            $thisDiv.addClass("itemClicked");
            items.push(ids);
            resultObj.val(items.join(','));
            count++;
        }
    }
});
var maxItems = 3;
$(function () {
    $(".box-items").click(function () {
        if ($(".itemSelected").length >= maxItems) {
            if ($(this).hasClass("itemSelected")) {
                $(this).removeClass("itemSelected");
            }
        } else {
            $(this).toggleClass("itemSelected");
        }
        var ids = "";    
        $(".itemSelected").each(function (index, item) {
          ids += $(item).attr("id")+",";
        });
        //i use slice to remove last comma
        $("#submitMe").val(ids.slice(0,-1));       
    });
});
<div class="box-items" id="1">click me</div>
<div class="box-items" id="2">click me</div>
<div class="box-items" id="3">click me</div>
<div class="box-items" id="4">click me</div>
<input id="submitMe" type="text" />