簡體   English   中英

jQuery在輸入元素旁邊添加一個元素

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

我有這個HTML輸入。

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

我正在嘗試在輸入字段旁邊添加somr元素。 我嘗試了append()prepend()但是它出錯了。

這是我的代碼:

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

這可能嗎? 我理想的輸出是這樣的

<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'>

您需要使用.after()方法。

在匹配的元素集中的每個元素之后插入由參數指定的內容。

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

.insertAfter()

在目標后面插入匹配元素集中的每個元素。

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

試試這個

    <!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