我想在 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/