如何使用KnockoutJS数据绑定iframe的内容? [英] How to data-bind content for an iframe using KnockoutJS?

查看:99
本文介绍了如何使用KnockoutJS数据绑定iframe的内容?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何人都可以告诉我如何使用Knockout将数据绑定到 iframe ?我试图按照以下方式执行此操作,但它没有按预期工作:

Can anyone please tell me how to bind data to an iframe using Knockout? I have tried to do this as below, but it is not working as expected:

<iframe data-bind ="attr: { src: testcontent}"></iframe>

和Javascript:

And Javascript:

var ViewModel = function (content) {
     this.testcontent = ko.observable(content);
};

ko.applyBindings(new ViewModel("Hello World!!"));

我想将文本Hello Content添加到 iframe 。任何人都可以帮我这个吗?

I want to add the text "Hello Content" into the iframe. Can anyone please help me on this?

推荐答案

这是一个稍微不同(更基本)的解决方案。它允许您拥有一个具有整个h​​tml结构的observable,并使用该数据填充iFrame。如果您更新html,iframe将使用新版本进行更新:

Here's a slightly different (more basic) solution to build on. It allows you to have an observable with an entire html structure, and fill the iFrame with that data. If you update the html, the iframe is updated with the new version:

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>")
});

您可以在视图中使用以下内容:

You can use this like this in your view:

<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>

参见这个jsfiddle 用于演示。 valueUpdate 只是在那里,所以演示更清晰,如果在更大的场景中这是一个好主意,这是有争议的。

See this jsfiddle for a demo. The valueUpdate is merely there so the demo is clearer, it's debatable if that's a good idea in bigger scenarios.

这篇关于如何使用KnockoutJS数据绑定iframe的内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆