gpt4 book ai didi

javascript - 需要切换选定的 div,并增加一个计数器

转载 作者:行者123 更新时间:2023-11-27 23:45:24 25 4
gpt4 key购买 nike

我需要允许用户点击一系列的 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="">

这是CSS:

.box-items {
padding: 5px;
margin: 5px 5px 5px 5px;
border-left: 4px solid #ff7b01;
min-height:75px;
width:100%;
display:inline-block;
background-color:#efefef;
cursor: pointer;
}

.itemClicked {background-color:grey;}

这是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 );


});


});

这是我为它创建的 fiddle :https://jsfiddle.net/3z1uoL8f/虽然它不起作用。

最佳答案

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

JS:

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));
});
});

HTML:

<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" />

fiddle :here

关于javascript - 需要切换选定的 div,并增加一个计数器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30132385/

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