簡體   English   中英

使用jQuery在輸入元素之后添加HTML

[英]Add HTML after an input element with jQuery

我試圖在使用jQuery的input字段后添加一些HTML,但是它不起作用,我不明白為什么。

<input type="text" value="secret password" maxlength="255" id="ripo" title="Password" class="ms-long ms-spellcheck-true">
$(document).ready(function() {
  jQuery("input[title='Password']").append('<P>test</P>');
});

append()用於在元素內添加內容,但是表單輸入不包含任何內容。 通常,您將使用val()設置其值。

但是,要實現所需的功能,請使用after()方法,而不是將內容插入到選定元素之后的DOM中:

 $(function() { $("#ripo").after('<P>test</P>'); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="text" value="secret password" maxlength="255" id="ripo" title="Password" class="ms-long ms-spellcheck-true"> 

您必須使用.after()方法。

append方法將內容插入匹配元素集中每個元素的末尾

after方法插入在該組匹配的元素中的每個元素之后的內容。

 $(document).ready(function() { jQuery("input[title='Password']").after('<p>test</p>'); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="text" value="secret password" maxlength="255" id="ripo" title="Password" class="ms-long ms-spellcheck-true"> 

另外,您可以通過以下方式使用insertAfter方法。

 $(document).ready(function() { $('<p>test</p>').insertAfter($("input[title='Password']")); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="text" value="secret password" maxlength="255" id="ripo" title="Password" class="ms-long ms-spellcheck-true"> 

您不能將HTML附加到輸入中。 但是您可以執行此操作(如果您想實際設置值):

$(document).ready(function() {
  jQuery("input[title='Password']").val('test');
});

盡管這不能回答已編輯的問題,但其他答案也可以解決在輸入之后附加元素的問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM