0

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

I'm trying to do it with the code below (on JSFiddle), but other solutions would be nice too. Thanks. Jquery is fine also.

Here's the 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>

Here's the 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 with comments (if needed): http://jsfiddle.net/bBf9j/7/

4

1 回答 1

0

您可以使用 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;
};
于 2013-10-23T03:09:59.960 回答