打开<div>在元素之前并在之后关闭它 [英] open <div> before element and close it after
问题描述
我正在创建一个 JQuery 插件.我需要在一些代码之前和 </div>
之后自动添加一个 <div id="id">
.
当我使用 $('#search').before('<div id=id>')
时,div 会自动关闭...
这是代码:
<input type="text"value="" id="search"></input><select id="select"></select><table id="table"></table><div id="当前"></div><div id="分页"></div>
我需要在#search"之前打开一个div"并在#pagination"之后关闭它
您当前代码的问题是您只能将整个元素插入到 DOM 中,也就是说,如果需要,包含其结束标记的元素一个.
要实现您想要的效果,您可以在选择所有必需元素后使用 wrapAll()
:
$('#search, #select, #table, #current, #pagination').wrapAll('<div id="id"/>');
#id {边框:1px 实心 #C00;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script><input type="text" value="" id="search"/><select id="select"></select><table id="table"><tr><td>#table</td></tr><div id="current">#current</div><div id="pagination">#pagination</div>
您可以通过将相同的类放在所有这些元素上而不是单独选择它们来使维护更容易.
I'm creating a JQuery Plugin.
I need to add automatically add a <div id="id">
before some code and the </div>
after.
When i do it with $('#search').before('<div id=id>')
the div automatically close...
this is the code:
<div id="id"></div>
<input type="text"value="" id="search"></input>
<select id="select"></select>
<table id="table"></table>
<div id="current"></div>
<div id="pagination"></div>
i need to open a "div" before "#search" and close it after "#pagination"
The issue with your current code is that you can only insert whole elements in to the DOM, that is to say an element which includes its closing tag should it require one.
To achieve what you want you can use wrapAll()
after selecting all the required elements:
$('#search, #select, #table, #current, #pagination').wrapAll('<div id="id" />');
#id {
border: 1px solid #C00;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<input type="text" value="" id="search" />
<select id="select"></select>
<table id="table">
<tr>
<td>#table</td>
</tr>
</table>
<div id="current">#current</div>
<div id="pagination">#pagination</div>
You could make this easier to maintain by putting the same class on all those elements instead of selecting them all individually.
这篇关于打开<div>在元素之前并在之后关闭它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!