简体   繁体   English

jQuery在输入元素旁边添加一个元素

[英]jquery add an element next to an input element

I have this html inputs. 我有这个HTML输入。

<input type='text' class='req-in' name='fname'>
<input type='text' class='req-in' name='lname'>

I am trying to do to add somr element next to the input field. 我正在尝试在输入字段旁边添加somr元素。 I tried append() and prepend() but it goes wrong. 我尝试了append()prepend()但是它出错了。

this is my code: 这是我的代码:

$('.req-in').blur(function() {
        $(this).append('<p>some text here for this field only!</p>');   
    });

is this possible? 这可能吗? my ideal output would be like this 我理想的输出是这样的

<input type='text' class='req-in' name='fname'><p>some text here for this field only!</p>
<input type='text' class='req-in' name='lname'>

You need to use .after() method. 您需要使用.after()方法。

Insert content, specified by the parameter, after each element in the set of matched elements. 在匹配的元素集中的每个元素之后插入由参数指定的内容。

$('.req-in').blur(function() {
    $(this).after('<p>some text here for this field only!</p>');   
});

or .insertAfter() .insertAfter()

Insert every element in the set of matched elements after the target. 在目标后面插入匹配元素集中的每个元素。

$('.req-in').blur(function() {
 $('<p>some text here for this field only!</p>').insertAfter($(this));
});

Try this one 试试这个

    <!DOCTYPE html>
<html>
<title>Stack HTML</title>
<link rel="stylesheet" href="../repo/css/bootstrap.css" type="text/css" />
<script src="https://code.jquery.com/jquery-2.1.3.js"></script>
<script src="../repo/js/bootstrap.js"></script>
<script src="../repo/js/jquery.validate.js"></script>
<head></head>
<body>

    <input type='text' class='req-in' name='fname'>
    <input type='text' class='req-in' name='lname'>

    <script>
        $(document.body).on('blur', '.req-in' ,function(){
            $(this).after('<p>some text here for this field only!</p>');
        });
    </script>
</body>
</html>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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