如何使用jQuery切换一个元素而不使用其他元素?

时间:2018-05-13 11:11:16

标签: javascript jquery html onclick

我很想知道如何在不切换其他元素的情况下切换一个元素......我只是不想每次都这样做:

HTML:

const orgsArr = [];
organizations.map(orgid => {
        this.afs.collection('users').doc<Organization>(orgid).valueChanges()
            .map(x => {
               orgsArr.push(x);
            }).subscribe();
});
return Observable.of(orgsArr);

JS:

<div class="share-toggle as-1"></div>

<div class="audio-share as1">
  <p>Some Text</p>
</div>

<div class="share-toggle as-2"></div>

<div class="audio-share as2">
  <p>Some Text</p>
</div>

有没有办法简单地写这个?请帮助... thx

2 个答案:

答案 0 :(得分:2)

您可以使用jQuery选择所有元素,className包含某个子字符串:

$('*[class*="as-"]')

这将选择DOM中的所有元素(*),其中className[class=""])其中"as-"位于*this

然后您可以使用以"as-"传递的元素来获取$('*[class*="as-"]').click(function () { let elemNum = this.className.match(/as-(\d+)/)[1]; $("as"+elemNum).slideToggle('fast'); }); 之后的元素编号并切换所需元素:

select max(spike) - min(spike)
from
 (  -- count per minute
    Select minute, count(beer) as spike
    from bar
    group by minute
 ) as dt

答案 1 :(得分:1)

我知道你已经接受了答案,但无论如何...... 在我看来,这是一个更好的解决方案。

为什么?
只有3行代码,而不使用任何正则表达式或部分类名...
有关更多详细信息,请参阅我的代码中的注释:

// You could use class^=[as-] to filter on the classes that start with as-,
// (the ^ would be better than a *, because more specific)
// But I suggest you to use the 'share-toggle' class, there's no need to complicate things here:
$('.share-toggle').on('click', function(){
  // The following will get the .audio-share element that is after the element we just clicked,
  // If your HTML structure is gonna stay well structured like this, it's the finest solution:
  $(this).next('.audio-share').slideToggle('fast');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="share-toggle as-1">[ CLICK HERE ]</div>

<div class="audio-share as1">
  <p>Some Text</p>
</div>

<div class="share-toggle as-2">[ CLICK HERE ]</div>

<div class="audio-share as2">
  <p>Some Text</p>
</div>

我希望你能考虑这个答案 我希望它会有所帮助!