.wrap不被包裹
问题描述:
我写了这个:.wrap不被包裹
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script> jQuery(document).ready(function($)
{ $("div.productInfo").wrap("<div id='productDetails' />");
$("ul.productInfo").wrap("<div id='specs' />");
$("#centerColumn" + "#rightColumn").wrap("<div id='test' />");
});
</script>
</head>
<body>
<p id="centerColumn" >This is a paragraph.</p>
<p id="rightColumn" >This is another paragraph.</p>
<div class="productInfo" > Wow </div>
</body>
</html>
而且#centerColumn没有得到包裹只有#rightColumn得到的包裹,为什么呢?
答
<html>
<head>
<script src="jquery.js"></script>
<script>
$(function() {
$("div.productInfo")
.wrap("<div id='productDetails'><div id='specs' /></div>");
$("#centerColumn, #rightColumn").wrapAll("<div id='test' />");
// or .wrap() instead of .wrapAll() depends on your intentions
});
</script>
</head>
<body>
<p id="centerColumn">This is a paragraph.</p>
<p id="rightColumn">This is another paragraph.</p>
<div class="productInfo"> Wow </div>
</body>
</html>
参见:
- .wrap()在jQuery的API
- .wrapAll()在jQuery的API
- Selectors在jQuery的文档
答
您使用此选择:
$("#centerColumn" + "#rightColumn")
的+
有连接运算符。它加入字符串,因此您的代码与此相同:
$("#centerColumn#rightColumn")
这显然没有用处。
我想你想的multiple selector:
$("#centerColumn, #rightColumn").wrap("<div id='test' />");
如果你想包装在相同祖先元素两列,你需要wrapAll
。这很可能是因为你正在给你的包装元素id
和id
属性必须是唯一的。
$("#centerColumn, #rightColumn").wrapAll("<div id='test' />");
答
也许正因为如此:
$("#centerColumn" + "#rightColumn").wrap("<div id='test' />");
应该是这样的:
$("#centerColumn,#rightColumn").wrap("<div id='test' />");
由于它的完成 – 2011-06-05 23:46:08