目标
阅读KnockoutJS 添加的内容data-product-id
。DOM
问题
我有以下标记:
<!-- ko foreach: Summary.products -->
<li data-bind="attr: { 'data-product-id': id }">
<div class="product-summary-actions float-right">
<button class="btn btn-danger btn-mini remove-item">
<i class="icon-remove"></i>
</button>
</div>
<div class="product-summary-quantity">
<h6 data-bind="text: infoComposition"></h6>
</div>
<div class="product-summary-description">
<p data-bind="text: name"></p>
</div>
</li>
<!-- /ko -->
如您所见,在带有绑定的注释之后的第一行有一个数据attr
绑定。看:
<li data-bind="attr: { 'data-product-id': id }">
当我使用 Chrome 的控制台检查我的 DOM 时,我有以下信息:
<li data-bind="attr: { 'data-product-id': id }" data-product-id="1">...</li>
如您所见,data-product-id
已成功应用。但是,当我不得不与他互动时,没有成功。
我的应用程序中有一个函数负责检查我的产品摘要中是否存在某个项目,以下循环执行此操作:
$(element).each(function () {
var $productId = $(this).closest("li").data("product-id"),
$match = $(".summary")
.find("li[data-product-id=" + $productId + "]").length > 0;
console.log($match);
});
总是返回false。换句话说,似乎 jQuery 不考虑data-product-id
由 KnockoutJS 生成的,因为如果我手动将data-product-id
属性添加到我的项目(如以下标记),一切正常。
<!-- ko foreach: Summary.products -->
<li data-product-id="1">
<div class="product-summary-actions float-right">
<button class="btn btn-danger btn-mini remove-item">
<i class="icon-remove"></i>
</button>
</div>
<div class="product-summary-quantity">
<h6 data-bind="text: infoComposition"></h6>
</div>
<div class="product-summary-description">
<p data-bind="text: name"></p>
</div>
</li>
<!-- /ko -->
好的...代码
我必要的HTML:
<button class="btn btn-success btn-small add"
title="Add to comparison list">
<i data-bind="attr: { class: ProductLayout.existsAtSummary($element) ?
'icon-minus' : 'icon-plus' }">
</i>
</button>
我的 JS:
function ProductLayoutViewModel() {
var self = this;
self.itemQuantity = ko.observable("");
self.itemQuantityValid = ko.computed(function () {
var q = self.itemQuantity();
return q != "0" && q != "00" && q != null && q != "";
}, this);
self.existsAtSummary = function (element) {
$(element).each(function () {
$productId = $(this).closest("li").data("product-id");
$match = $(".summary")
.find("li[data-product-id=" + $productId + "]").length;
if (!$match)
return true;
else
return false;
});
});
};
ViewModel = {
Summary: new SummaryViewModel(),
ProductLayout: new ProductLayoutViewModel()
};
$.ajax({
url: "/ProductsSummary/List?output=json",
dataType: "json",
success: function (data) {
var mappingOptions = {
create: function (options) {
return (new (function () {
this.finalMeasure = ko.computed(function () {
return this.quantity() > 1 ?
this.measure() + "s" : this.measure();
}, this);
this.infoComposition = ko.computed(function () {
return this.quantity() + ' ' + this.finalMeasure();
}, this);
ko.mapping.fromJS(options.data, {}, this);
})());
}
};
ViewModel.Summary.products = ko.mapping.fromJS(data, mappingOptions);
ko.applyBindings(ViewModel);
}
});
有人知道我该如何解决这个问题?谢谢!