假设我有以下的淘汰视图,如何使用javascript获取实际生成代码的outerHtml。每当我尝试选择" table_1"的外部HTML时使用javascript我最终会得到包含敲除标记的html,而不是屏幕上可见的实际HTML。
<table id="table_1">
<thead>
<tr>
<th>Name</th>
<th>Date</th>
</tr>
</thead>
<tbody>
<!-- ko foreach: $data.Rows -->
<tr>
<td data-bind="text: Name"></td>
<td data-bind="text: Date"></td>
</tr>
<!-- /ko -->
</tbody>
答案 0 :(得分:0)
敲除组件可以提供绑定元素。
请参阅http://knockoutjs.com/documentation/component-registration.html
ko.components.register('printable-component', {
viewModel: {
createViewModel: function(params, componentInfo) {
console.log(componentInfo.element);
}
}
});
使用这种机制a&#39;可打印&#39;可以开发可以访问绑定元素的innerHTML的组件。
// This is a simple *viewmodel* - JavaScript that defines the data and behavior of your UI
function AppViewModel() {
this.Rows = [{
Name: 'Joseph',
Date: '2017-02-13'
}, {
Name: 'Mary',
Date: '2017-02-13'
}];
}
// define a printable component
ko.components.register('printable-component', {
viewModel: {
// create using the factory function
// see http://knockoutjs.com/documentation/component-registration.html
createViewModel: function(params, componentInfo) {
// return a new ViewModel for the component
return new function() {
this.rows = params.rows;
// track the componentInfo
this.componentInfo = componentInfo;
// print method function
this.print = function() {
alert(componentInfo.element.innerHTML);
}
}
}
},
// the component template
// note: can be jsx
// note: can be defined in html using internal template nodes
// note: print button can be hidden using CSS or by defining it outisde the printable component and use the params to start the print function
template: '<table><thead><tr><th>Name</th><th>Date</th></tr></thead><tbody><!-- ko foreach: $data.rows --> <tr><td data-bind="text: Name"></td><td data-bind="text: Date"></td></tr><!-- /ko --></tbody></table><a href="javascript:void();" data-bind="click:print">print</a>'
});
// Activates knockout.js
ko.applyBindings(new AppViewModel());
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<printable-component params="rows:$data.Rows"></printable-component>
&#13;