谁能告诉我如何使用Knockout将数据绑定到iframe
?我尝试过这样做,但没有达到预期的效果:
<iframe data-bind ="attr: { src: testcontent}"></iframe>
和Javascript:
var ViewModel = function (content) {
this.testcontent = ko.observable(content);
};
ko.applyBindings(new ViewModel("Hello World!!"));
我想将文本"Hello Content“添加到iframe
中。有人能在这方面帮我一下吗?
发布于 2014-10-03 08:25:36
警告:这显然有安全隐患!只有使用你绝对信任的代码才能做到这一点。
这里有一个基本的、简单的解决方案可供构建。它允许您拥有一个具有整个html结构的可观察对象,并用该数据填充iFrame。如果您更新html,iframe将使用新版本进行更新:
ko.bindingHandlers.iframeContent = {
update: function(element, valueAccessor) {
var value = ko.unwrap(valueAccessor());
element.contentWindow.document.close(); // Clear the content
element.contentWindow.document.write(value);
}
};
ko.applyBindings({
myHtml: ko.observable("<html>\n<head><title>Test</title></head>\n<body>\n\nMy <em>fine</em> text.\n\n</body>\n</html>")
});
您可以在您的视图中像这样使用:
<p>Edit your html:</p>
<textarea data-bind="value: myHtml, valueUpdate: 'afterkeydown'"></textarea>
<p>And see it appear in an iframe:</p>
<iframe data-bind="iframeContent: myHtml"></iframe>
有关演示,请参阅this jsfiddle。valueUpdate
只是为了让演示更清晰,在更大的场景中这是否是一个好主意是有争议的。
发布于 2013-03-20 13:45:22
编辑:小提琴已更新。
http://jsfiddle.net/sujesharukil/NnT78/10/
您需要为此创建一个自定义绑定处理程序。我就用过http://jsfiddle.net/mbest/GYRUX/的一个这样的例子
并根据您的需要对其进行了更改。看看这两种方法,看看哪种方法能满足你的需求。
ko.bindingHandlers.bindIframe = {
init: function(element, valueAccessor) {
function bindIframe() {
try {
var iframeInit = element.contentWindow.initChildFrame,
iframedoc = element.contentDocument.body;
} catch(e) {
// ignored
}
if (iframeInit)
iframeInit(ko, valueAccessor());
else if (iframedoc){
var span = document.createElement('span');
span.setAttribute('data-bind', 'text: someProperty');
iframedoc.appendChild(span);
ko.applyBindings(valueAccessor(), iframedoc);
}
};
bindIframe();
ko.utils.registerEventHandler(element, 'load', bindIframe);
}
};
发布于 2013-03-20 20:26:10
你可以有这样的代码,工作起来绝对很好:
// This is a simple *viewmodel* - JavaScript that defines the data and behavior of your UI
function AppViewModel() {
this.externalUrl = ko.observable("http://www.w3schools.com");
}
// Activates knockout.js
ko.applyBindings(new AppViewModel());
或
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Test IFrame</title>
<script src="Scripts/jquery-1.7.1.js"></script>
<script src="Scripts/knockout-2.2.1.js"></script>
<script>
$(document).ready(function () {
// This is a simple *viewmodel* - JavaScript that defines the data and behavior of your UI
function AppViewModel() {
this.externalUrl = "http://www.w3schools.com";
}
// Activates knockout.js
ko.applyBindings(new AppViewModel());
});
</script>
</head>
<body>
<iframe class="iframe" id="iframe" style="width: 700px; height: 700px" data-bind="attr: { src: externalUrl }"></iframe>
</body>
</html>
https://stackoverflow.com/questions/15523457
复制相似问题