使用onclick按钮在Javascript中添加输入字段 [英] Adding input fields in Javascript with onclick button

查看:136
本文介绍了使用onclick按钮在Javascript中添加输入字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直习惯使用jquery或其他javascript框架,但是现在我没有框架可以使用,所以我想看看是否有人知道如何在可能的情况下使用纯JavaScript.

Im always used to using jquery or other javascript frameworks but right now I have no frameworks to use so i wanted to see if anyone knows how i can do this in straight javascript if possible.

基本上我有这样的div

Basically i have a div like this

<input type="button" id="more_fields" onclick="add_fields();" value="Add More" />

<div id="room_fileds">
    <div class='label'>Room 1:</div>
    <div class="content">
        <span>Width: <input type="text" style="width:48px;" name="width[]" value="" /><small>(ft)</small> X </span>
        <span>Length: <input type="text" style="width:48px;" namae="length[]" value="" /><small>(ft)</small</span>
    </div>
</div>

我需要的是,当单击添加更多按钮时,我基本上需要添加更多的宽度和长度字段,或者创建像上面那样的带有所有div的整个结构,或者只是在现有字段下面插入新的span标签.一个.

What i need one is when the add more button is clicked i need to basically add more width and length fields either creating a entire structure like the one above with all the divs or just inserting new span tag with the fields below the existing ones.

我知道如何使用jquery或原型框架,但是不幸的是我不能为此使用任何框架.有谁知道如何做到这一点.我会为此完成代码iv,但我什至不知道在哪里开始.

I know how to do it with jquery or prototype framework but unfortunatley I cannot use any frameworks for this. Does anyone have any idea how to do it. I would post code iv done for this but I dont even know where to beging.

推荐答案

您可以使用innerHTML属性添加内容.在span元素周围的div中添加id="wrapper",然后就可以

You can use the innerHTML property to add content. Add a id="wrapper" to the div surrounding your span elements and then you can do

var dummy = '<span>Label: <input type="text"><small>(ft)</small></span>\r\n';
document.getElementById('wrapper').innerHTML += dummy;      

当然您不需要id,并且可以使用其他DOM方法来访问div,但是我发现使用id更容易,更清洁.这是一个快速的小提琴

Of course you don't need the id and can use other DOM methods to get to the div, but I find using ids easier and cleaner. Here's a quick fiddle

还请注意,您不应内联CSS代码,也不要将javascript调用直接附加在DOM元素内.分离DOM,Javascript和CSS将使您的生活更轻松.

Also note that you shouldn't inline your css code, neither attach your javascript calls directly inside the DOM elements. Separating DOM, Javascript and CSS will make your life easier.

这篇关于使用onclick按钮在Javascript中添加输入字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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