简体   繁体   中英

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

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/

you can access the document object of iframe using contentDocument

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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