我需要显示名称是字符串变量结果的块 方法.find()可以采用变量吗?
var className;
$('.game--test').find('.assault--test').click(function(){
className = '.assault-res';
alert(className);
});
$('.game--test').find('.medic--test').click(function(){
className = '.medic-res';
alert(className);
});
$('.game--test').find('.gunner--test').click(function(){
className = '.gunner-res';
alert(className);
});
$('.game--test').find('.radioman--test').click(function(){
className = '.radioman-res';
alert(className);
});
$('.game--test2').find(className).show();
答案 0 :(得分:1)
如果我理解正确,你需要听一下动态类名的事件。
$('.game--test2').find('.'+classname).show();
// or
$('.game--test2 .' + classname).show();
you can also have one listener for any class that ends with `--test` and show a message depending on the element that was clicked
$('.game--test2 [class$=--test]').on('click', function(e) {
alert($(event.target).attr('class') + ' was clicked');
});
答案 1 :(得分:0)
此版本使用元素上的数据目标来确定应更改哪个其他元素。它还使用公共类来查找相似的元素。像这样逻辑的好处是标记描述了你的元素,如果你改变了事物的相关性,你的javascript逻辑就有可能不必改变。
还将绑定更改为委托原因,为什么不呢? :)
$('.game--test').on('click', '.test', function(e){
$('.game--test2 .res')
.removeClass('active')
.filter('.'+ e.target.dataset.target)
.addClass('active');
});
.res {
display: none;
}
.res.active {
display: inherit;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="game--test">
<button class="test" data-target="assault-res">Assault</button>
<button class="test" data-target="medic-res">Medic</button>
<button class="test" data-target="gunner-res">Gunner</button>
<button class="test" data-target="radioman-res">Radioman</button>
</div>
<div class="game--test2">
<div class="res assault-res">Assault Stuff</div>
<div class="res medic-res">Medic Stuff</div>
<div class="res gunner-res">Gunner Stuff</div>
<div class="res radioman-res">Radioman Stuff</div>
</div>