使用JUST代码在div中创建工作表单

时间:2012-01-28 16:03:57

标签: javascript jquery

我有一个div:

<div id="test">Text to be removed</div>

如何使用JUST代码将此完整表单添加到div中(从零开始,意味着表单元素不存在于页面中的任何位置):

<form name="input" action="html_form_action.asp" method="get">
Edit: <input type="text" name="tex" value="Some text here to edit"/>
<input type="submit" value="Submit" />
</form> 

1 个答案:

答案 0 :(得分:2)

那怎么样......

$('#test').html('<form name="input" action="html_form_action.asp" method="get">' +
                    'Edit: <input type="text" name="tex" value="Some text here to edit"/>' +
                    '<input type="submit" value="Submit" />' +
                 '</form>');

...或

$('<form>',{name:'input',action:"html_form_action.asp",method:'get'})
    .append('Edit: ')
    .append($('<input>',{type:'text',name:'tex',value:'Some text here to edit'}))
    .append($('<input>',{type:'submit',value:'Submit'}))
    .appendTo($('#test').empty());

或使用原生API ...

var test_div = document.getElementById('test');

test_div.innerHTML = '';

var form = test_div.appendChild(document.createElement('form'));

form.name = 'input';
form.action = 'html_form_action.asp';
form.method = 'get';

form.appendChild(document.createTextNode('Edit: '));

var input = form.appendChild(document.createElement('input'));
input.type = 'text';
input.name = 'tex';
input.value = 'Some text here to edit';


input = form.appendChild(document.createElement('input'));
input.type = 'submit';
input.value = 'Submit';

或者使用本机API和辅助函数......

function createAndInsert(parent, tag, props, clear_first) {
   var el;

    if(typeof parent === 'string')
        parent = document.getElementById(parent);

    if(clear_first)
        parent.innerHTML = '';

    if(tag === ':text')
        el = parent.appendChild(document.createTextNode(props));
    else {
        el = parent.appendChild(document.createElement(tag));

        for(var n in props)
            el[n] = props[n];
    }
    return el;
}

则...

var form = createAndInsert('test', 'form', {
   name: 'input',
   action: 'html_form_action.asp',
   method: 'get'
}, true);

createAndInsert(form, ':text', 'Edit: ');

createAndInsert(form, 'input', {type:'text',name:'tex',value:'Some text here to edit'});

createAndInsert(form, 'input', {type:'submit',value:'Submit'});