我想知道为什么jQuery不允许" +"标志。这是一个如何使用" 1"和" 3"但不是" 2 +"。只需将鼠标悬停在每个div上方的文本上。
<div id="div-2+"></div>
$('a.hover').mouseover(function() {
dataI = $(this).data('i');
$('div#div-' + dataI).addClass('h');
});
$('a.hover').mouseout(function() {
dataI = $(this).data('i');
$('div#div-' + dataI).removeClass('h');
});
&#13;
a {
display: inline-block;
width: 100px;
margin: 60px 20px 60px 0;
text-align: center;
}
div {
display: inline-block;
width: 100px;
height: 100px;
margin-right: 20px;
background-color: #ddd;
}
div.h {
background-color: #f00;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<a class="hover" data-i="1">DIV 1</a>
<a class="hover" data-i="2+">DIV 2+</a>
<a class="hover" data-i="3">DIV 3</a>
<br />
<div id="div-1"></div>
<div id="div-2+"></div>
<div id="div-3"></div>
&#13;
答案 0 :(得分:10)
最有可能是因为the plus sign is the adjacent CSS selector导致SQuery选择器库jQuery使用它来假设你指的是一个相邻的选择器。
解决此问题的一种方法是使用选择id
属性的属性选择器。虽然很多人会争辩在id
中添加一个加号是个坏主意。
$('a.hover').mouseover(function() {
dataI = $(this).data('i');
$('div[id="div-' + dataI + '"]').addClass('h');
});
$('a.hover').mouseout(function() {
dataI = $(this).data('i');
$('div[id="div-' + dataI + '"]').removeClass('h');
});
&#13;
a {
display: inline-block;
width: 100px;
margin: 60px 20px 60px 0;
text-align: center;
}
div {
display: inline-block;
width: 100px;
height: 100px;
margin-right: 20px;
background-color: #ddd;
}
div.h {
background-color: #f00;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<a class="hover" data-i="1">DIV 1</a>
<a class="hover" data-i="2+">DIV 2+</a>
<a class="hover" data-i="3">DIV 3</a>
<br />
<div id="div-1"></div>
<div id="div-2+"></div>
<div id="div-3"></div>
&#13;
答案 1 :(得分:2)
注意,&#34;解决方法&#34;
尝试使用if(count($coll) > 1)
css
&#13;
a {
display: inline-block;
width: 100px;
margin: 60px 20px 60px 0;
text-align: center;
}
div {
display: inline-block;
width: 100px;
height: 100px;
margin-right: 20px;
background-color: #ddd;
}
a.hover[data-i="1"]:hover ~ div[id$="1"],
a.hover[data-i="2+"]:hover ~ div[id$="2+"],
a.hover[data-i="3"]:hover ~ div[id$="3"] {
background-color: #f00;
}
&#13;
答案 2 :(得分:1)
@Alexander O'Mara做了很好的解释为什么它不起作用并展示了一个体面的解决方案。
另一种解决方法是通过在反斜杠前加上反转符来逃避加号。
dataI = dataI.replace('+', '\\+');
来自jQuery documentation for Selectors:
使用任何元字符(例如
!"#$%&'()*+,./:;<=>?@[]^`{|}~
)作为名称的字面部分,它必须 使用两个反斜杠进行转义:\\
。例如,一个元素id="foo.bar"
,可以使用选择器$("#foo\\.bar")
。 W3C CSS 规范包含complete set of rules regarding valid CSS selectors。同样有用的是Mathias Bynens在CSS character escape sequences for identifiers上的博客文章。
另请注意,document.querySelector()
在给定选择器#div-2+
时会引发以下错误:
SyntaxError: An invalid or illegal string was specified.