如何将类添加到所选元素的父级
我想在元素的父元素中添加类。
dom的结构是:
<ul class="companies">
<li>
<a id=""></a>
<a id=""></a>
</li>
<li>
<a id=""></a>
<a id=""></a>
</li>
</ul>
所有“a”元素的id都是自动的。
我想将类添加到所选“a”的父级“li”。
这是我的代码:
$(".companies li a:selected").parent("li").addClass('selected');
selectDealer($(".companies li a:selected").attr("id"));
但是当我单击一个元素“a”时,其父元素“li”将不会被选择。
有谁知道为什么?
谢谢
I want to add class in an element's parent.
The structure of the dom is:
<ul class="companies">
<li>
<a id=""></a>
<a id=""></a>
</li>
<li>
<a id=""></a>
<a id=""></a>
</li>
</ul>
All the ids of "a" elements are automatic.
I want to add class to the parent "li" of selected "a".
Here is my code:
$(".companies li a:selected").parent("li").addClass('selected');
selectDealer($(".companies li a:selected").attr("id"));
But when i click one element "a", its parent "li" will not be selected.
Does anyone know why?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我认为您所追求的是这里的
点击
处理程序::selected
用于selected
元素,例如上面只是为了说明,更高效的版本会使用
.delegate()
像这样:I think what you're after is a
click
handler here::selected
is forselected
elements, like<option>
elements in a<select>
for example. If you want something to happen on an event, likeclick
, use an event handler like I have above. Inside the handler,this
will refer to the element the event's happening on.The above is for illustration, a more efficient version would use
.delegate()
like this:链接不能为“:selected”,这只适用于选项元素。因此,您的初始选择器失败了。
A link can't be ':selected', this only applies to option elements. Your inital selector is thus failing.
你确定 a:selected 可以这样使用吗?未经测试我会说这就是错误
Are you sure a:selected can be used like that? Without testing I'd say that's the error