gpt4 book ai didi

javascript - 统计

转载 作者:行者123 更新时间:2023-11-28 01:35:43 33 4
gpt4 key购买 nike

在 jquery 的帮助下,我能够动态添加/删除输入字段。但我在尝试计算标签数量 data-bind='personCount' 并在 html 中显示结果时遇到困难。例如,对于每个项目都显示 Person #1、Person #2、Person #3 等。我已经能够在选择下拉菜单中使用 items 来实现此操作。如何计算标签 data-bind='personCount', 显示Person #1` 等的次数?这是JSFIDDLE

Jquery

var template;

function Person() { //we use this as an object constructor.
this.personCount= 0;
this.firstName = '';
}

function renderItem() {
template = template || $("[data-template=item]").html();
var el = $("<div></div>").html(template);
return el; // a new element with the template
}

function addItem() {
var person = new Person(); // get the data
var el = renderItem(); // get the element

el.find("[data-bind=personCount]").keyup(function (e) {

});

el.find("[data-bind=firstName]").keyup(function (e) {
person.firstName = this.value;
});

return {
el: el,
person: person
}
}

var stuff = [];
$("[data-action='add']").click(function(e){
var item = addItem();
$("body").append(item.el);
stuff.push(item);
});

$("[data-action='remove']").click(function(e){
if(stuff.length > 1) {
var item = stuff.pop()
item.el.remove();
}
});

var item = addItem();
$("body").append(item.el);
stuff.push(item);


});

HTML

<div>
<script type='text/template' data-template='item'>
<ul class="clonedSection">
<label data-bind='personCount' class="personCount">Person # {person_count}</label>
<li style="list-style-type: none;">
<input type="text" data-bind='firstName' placeholder="First Name" required pattern="[a-zA-Z]+" />
</li>
</ul>
</script>
<input type='button' value='add' data-action='add' />
<input type='button' value='remove' data-action='remove' />
</div>

最佳答案

写:

var count = $("body").find(".personCount[data-bind='personCount']").length;
$("body").find(".personCount[data-bind='personCount']:last").text("Person # {"+count+"}");

$("body").find(".personCount[data-bind='personCount']").length 将为您提供具有 personCount 类的元素数量> 和属性 data-bind='personCount'

Updated fiddle here.

关于javascript - 统计<label>元素在页面中出现的次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21568510/

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