javascript - 在 jquery 中访问一个类的元素不起作用

标签 javascript jquery html css

我想在 jquery 中使用 $this 访问不同的 ID(具有相同的名称),但它不起作用。 我希望当一个 super 英雄被点击时只有他的 friend ,他自己只能改变他们的等级。

<!DOCTYPE html>
<html>
<head>
<title>Try jQuery 2.0.0 Online</title>
<script src="http://code.jquery.com/jquery-2.0.0.min.js"></script>
<script>
$(document).ready(function() {
    $('.shikhar').click(function(){
            $(this).find('#a').click(function(){
                $(this).find('#b').addClass("selected");
                $(this).find('#a').addClass("highlight");
            });
            $(this).find('#b').click(function(){
                $(this).find('#a').addClass("selected");
                $(this).find('#b').addClass("highlight");
            });
        });
    });
</script>
<style>
.selected { 
    color:red; 
}
.highlight { 
    background:yellow; 
}
</style>
</head>
<body>
<div class="shikhar">
    <div id="a">Spiderman</div>
    <div id="b">Hulk</div>
</div>
<div class="shikhar">
    <div id="a">Superman</div>
    <div id="b">Batman</div>
</div>
</body>
</html>

最佳答案

ID 属性必须是唯一的。一旦找到具有匹配 ID 的 第一个 元素,JavaScript 就会停止搜索。只需将这些 ID 更改为类即可:

<div class="a">Spiderman</div>
...
<div class="a">Superman</div>

然后将您的 jQuery 选择器更改为 $('.a')$('.b'):

$(this).find('.a').click(function(){
    $(this).find('.b').addClass("selected");
    $(this).find('.a').addClass("highlight");
});

关于javascript - 在 jquery 中访问一个类的元素不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23831448/

相关文章:

javascript - 如何在不使用按钮的情况下选择 html 表格中的一行?

javascript - 在另一个 div 中滚动 div

javascript - 单击时在搜索输入上附加文本

Javascript在循环中隐藏对象

javascript - 使用 CSS 或 javascript/jQuery,我应该使用哪种方法使我网站的导航栏看起来更像 3d 风格?

php - 下拉菜单无法排序

javascript - 查找元素并替换它

jquery - 使用 Cheerio 解析表

javascript - 如何从文档中插入 HTML ASCII 艺术?

html - 如何在没有固定高度的情况下使动态div溢出