javascript - 通过 jQuery 使用表单输入值创建 HTML 元素

标签 javascript jquery html

我正在尝试使用表单值自动实现 HTML。
当用户在表单中输入信息时,JS 将为他创建相应的 HTML。

例如。

<div class="row" id="1">
    <div class="form-group col-lg-2">
        <select class="form-control" name="tag">
            <option value="p" selected>p</option>
            <option value="br">br</option>
        </select>
    </div>
    <div class="form-group col-lg-2">
        <select class="form-control" name="class">
            <option value="Day" selected>Day</option>
            <option value="BlockTime">BlockTime</option>
            <option value="BlockTitle">BlockTitle</option>
            <option value="Session">Session</option>
            <option value="Person">Person</option>
            <option value="Firm">Firm</option>
        </select>
    </div>
    <div class="form-group col-lg-7">
        <textarea class="form-control" rows="3" name="content"></textarea>
    </div>
    <div class="form-group col-lg-1">
        <input type="button" class="btn btn-default" onclick="addLine()" value="Add">
    </div>
</div>

用户选择了P、Day、Test消息,然后按下“Add”按钮,该按钮将调用函数addLine()。主要部分如下,我没写对。

var currentTag = currentLine.find("select[name='tag'] option:selected").text();
var currentClass = currentLine.find("select[name='class'] option:selected").text();
var currentText = currentLine.find("textarea").val();

var new_content = $("<currentTag></currentTag>").addClass(currentClass).html(currentText);

现在currentTag将获取值“p”,currentClass将获取“Day”,currentText将获取“Test message”,这已经完成了。

这就是我想要的,jQuery 创建这样的 HTML 代码:

<p class="Day">Test message</p>

我想将 HTML 代码存储到名为 new_content 的变量中。 ...

最佳答案

如果您有这些元素的容器,则可以将它们附加到其中:

首先,您要将新行设置为变量:

var newElements = [];
var i = 0; //Make an index counter so you can use it later if you want to.  This is optional
/* Do your selection script */
    var htmlElement = "<" + currentTag + " class='" + currentClass + "'>" + currentText + "</" + currentTag + ">";
    newElement.push(htmlElement, i);
    $('.container').append(htmlElement);
    i++;  //increment your i to create an index
/* Make sure all of this is inside your selection script. */

关于javascript - 通过 jQuery 使用表单输入值创建 HTML 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22999249/

相关文章:

javascript - 从嵌套数据结构中删除元素

javascript - HERE Api Map 只显示实际 map 的一小部分,不具有交互性

jquery - 如何将用户 ID 传递到 django ajax post 中?

html - 根据文本更改不同td的宽度

javascript - 使用 JS 将类应用于父元素

javascript - "$.______ is not a function"错误。怎么了?

jquery - 如何获取当前的 CSS 媒体参数值?

javascript - 解析分组的json

html - 如何顺利隐藏显示图片?网页格式

javascript - 如何为 Javascript 使用平滑滚动?