借助jquery,我能够动态添加/删除输入字段。但是我很难计算标签data-bind='personCount'
的数量并在html中显示结果。例如,对于每个显示Person #1, Person #2, Person #3
的项目,等等。我已经能够在选择下拉菜单中使用items
进行此操作。如何计算标签data-bind='personCount', to show
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.