如何使用jQuery在输入中添加<div>元素

时间:2016-02-12 05:44:34

标签: javascript jquery html css

<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
    <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
    <script>
        $(document).ready(function () {
            $("#usr").click(function () {
                var divElement = "<div style='color:yellow;'>more text</div>";
                $('#usr').val($('#usr').val() + divElement);
            });
        });
    </script>
</head>
<body>
    <input class="form-control" id="usr">
</body>
</html>

我想在文本框中添加这个div元素,但它作为字符串和显示。

是否可以这样做,或者是否有任何其他方式来执行此操作。谢谢

5 个答案:

答案 0 :(得分:1)

无法将div置于input内。

Check Here

答案 1 :(得分:1)

在输入框中添加div是不可能的,但是如果你在使用它时没有这样的问题,你可以使用contenteditable div而不是输入字段。

你可以在里面添加任何内容。

http://www.w3schools.com/tags/att_global_contenteditable.asp

答案 2 :(得分:0)

它将输入和返回对象类型添加为输出

<!DOCTYPE html>
 <html>
 <head>
 <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
 <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js">     </script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#usr").click(function(){

    $('#usr').val($(this).html('<div></div>'));
});
});
</script>
</head>
<body>
<input class="form-control" id="usr">

答案 3 :(得分:0)

$(document).ready(function(){
$("#usr").click(function(){
var divElement="<div style='color:yellow;'>more text</div>";
    $('#usr').val($('#usr').val() + divElement);
});
});

当你想添加任何html元素时,请使用如下的追加:

$('#usr').append($('#usr').val() + divElement);

答案 4 :(得分:0)

您不能在div内放置input任何其他元素。您可以在输入中插入简单文本。

像:

$(document).ready(function(){
$("#usr").click(function(){
var divElement="more text";
    $('#usr').val($('#usr').val() + divElement);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<input class="form-control" id="usr">