如何在div中包含按钮的HTML?

kni*_*ion 2 html javascript jquery

使用jQuery,我试图将每个button元素的HTML 包装成div.

jsfiddle链接

jQuery的

$('button').each(function(){
    var markup = $(this).html();
    console.log(markup);


    //This doesn't work
    //markup.each(function(){
    //  $(this).wrap('<div></div');
    //})

    //This doesn't work either
    //markup.wrap('<div></div>');
});
Run Code Online (Sandbox Code Playgroud)

我得到TypeError: markup.wrap is not a function了最后一次没有工作的尝试和类似于第一次的事情

我的最终目标是:在a中包装每个按钮的内容(它也可以包括JSFiddle中显示的标签)div

有任何想法吗?

Rok*_*jan 5

你不需要迭代.each().
$("button")已经是你所有"button"元素的集合.

将选择器包装到另一个元素中:

http://api.jquery.com/wrap/

$("button").wrap("<div />");
Run Code Online (Sandbox Code Playgroud)
div{
  background: #0FF1CE;
  padding: 10px;
  margin: 5px;
}
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Button 1</button>
<button>Button 2</button>
Run Code Online (Sandbox Code Playgroud)

将元素的内容包装到另一个元素中:

如果要将元素包含的所有内容包装到另一个元素中,请使用:http:
//api.jquery.com/wrapinner/

为了您的通知,这是不正确的HTML标记使用的块级元素内<button> http://www.w3.org/TR/2012/WD-html5-20120329/the-button-element.html#the-button-element →交通等等让我们<span>在这个例子中使用:

$("button").wrapInner("<span />");
Run Code Online (Sandbox Code Playgroud)
span{
  background: #0FF1CE;
  color:      #EFFEC7;
}
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button><i>Button</i> <b>1</b></button>
<button><i>Button</i> <b>2</b></button>
Run Code Online (Sandbox Code Playgroud)

  • @knitevision它是无效的标记,无论如何用内部(块级)HTML元素(如DIV)填充"<button>".`<span>`很好但不是`<div>` (2认同)