繁体   English   中英

如何将动态创建的输入(或文本框)值发送到iframe,并在iframe中将其显示为HTML?

[英]How do I send my dynamically created input (or textbox) values to an iframe and show it as HTML inside the iframe?

如何将动态创建的输入(或文本框)值发送到iframe,并在iframe中将其显示为HTML?

我正在尝试使用下面的代码(在JSFiddle上)做到这一点,但是其他解决方案也将很好。 谢谢。 jQuery也很好。

这是HTML:

<a href="#" id="new" rel="create">new</a><br>
<a href="#" id="another" rel="create">another</a><br>

<input id="thisButton" type="button" name="Display" value="Edit HTML Below then Click to Display"/>

<iframe id="iframetest" src="" style="background: White;"></iframe>

这是Javascript:

var counter = {};

var myHTML = {
    'new': '<input id="test%n" name="test" value="<b>blah</b> blah blah %n">',
    'another': '<input id="another%n" name="test" value="<b>cool</b> COOL! %n">'
};

var htmlForId = {
    'foo': ['a','b','c'],
    'bar': ['d','e','f']
}

var createEls = document.querySelectorAll('a[rel=create]');
for(var i = 0; i < createEls.length; i++) {

  createEls[i].onclick = create;
}

function create() {
    var id = this.id;

    var div = document.createElement('div');
    div.className = 'create';
    if (counter[id]===undefined) { counter[id] = 1; }
    var thecurrentid = counter[id];
    div.id = id + counter[id]++;

    if (div.id in myHTML) {
        div.innerHTML = myHTML[div.id].replace(/%n/g, thecurrentid);
    } else if (this.id in myHTML) {
        div.innerHTML = myHTML[this.id].replace(/%n/g, thecurrentid);
    } else {
        div.innerHTML = div.id;
    }
    document.body.appendChild(div);

    return false;
}

var myArray = [
    'b<strong>l</strong>a bla bla', // index 0
    'foo', // index 1
    'test' // index 2
];
function appendArray(a) {
    for(var i = 0; i < a.length; i++) {
        var div = document.createElement('div');
        div.className = 'loop';
        div.innerHTML = a[i];
        document.body.appendChild(div);
    }
}

jsfiddle: http : //jsfiddle.net/bBf9j/8/

带有注释的jsfiddle(如果需要): http : //jsfiddle.net/bBf9j/7/

您可以使用contentDocument访问iframe的文档对象

document.getElementById("thisButton").onclick = function(){
    var html = "<b>Dynamic Content</b>"; //TODO: get the value dynamically from textbox
    document.getElementById("iframetest").contentDocument.body.innerHTML = html;
};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM