[英]Counting the number of times a <label> element appears in page
借助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'
的元素数量。
这是您的提琴的更新http://jsfiddle.net/6MXrN/4/
我认为这就是您要寻找的。 我已经做了
$('label[data-bind="currentPerson"]).length
获取标签元素的数量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.