首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >onClick元素将类名添加到具有相同类名的相关div中

onClick元素将类名添加到具有相同类名的相关div中
EN

Stack Overflow用户
提问于 2015-09-26 14:01:23
回答 3查看 2K关注 0票数 2

我有两个容器。第一个容器(.links)具有带有类名为block-1, block-2等的锚标记.

第二个容器(.highlight-block)具有与block-1, block-2等相同的类名.

小提琴

代码语言:javascript
复制
<div class="links">
    <a href="#" class="lb block-1">Highlight Block 1</a>
    <a href="#" class="lb block-2">Highlight Block 2</a>
    <a href="#" class="lb block-3">Highlight Block 3</a>
    <a href="#" class="lb block-4">Highlight Block 4</a>
    <a href="#" class="lb block-5">Highlight Block 5</a>
    <a href="#" class="lb block-6">Highlight Block 6</a>
</div>

<div class="highlight-block">
    <div class="cb block-1 active">This is Block 1</div>
    <div class="cb block-2">This is Block 2</div>
    <div class="cb block-3">This is Block 3</div>
    <div class="cb block-4">This is Block 4</div>
    <div class="cb block-5">This is Block 5</div>
    <div class="cb block-6">This is Block 6</div>
</div>

如果我点击<a href="#" class="lb block-2">Highlight Block 2</a>.links容器.<div class="cb block-2">This is Block 2</div>应该上.active课程

jQuery

代码语言:javascript
复制
$(document).ready(function () {
    $('.links a').click(function () {
        $('.highlight-block').find('.cb').toggleClass('active');
    });
});

CSS

代码语言:javascript
复制
body {
    font-family:arial;
    font-size:12px;
}
.links .lb {
    margin-left:5px;
}
.highlight-block .cb {
    background:#eee;
    padding:10px;
    border:1px solid #666;
    margin:5px;
}
.highlight-block .cb.active {
    background:#5cb85c;
    border-color:#1E6B1E;
    color:#fff;
} 
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2015-09-26 14:06:46

如果它们的顺序相同,那么使用元素的索引要比使用常见的类名要容易一些:

代码语言:javascript
复制
// bind a click-handler for the <a> elements that are descendants
// of a '.links' element:
$('.links a').click(function () {

    // gets the index of the clicked element
    // from amongst its siblings:
    var i = $(this).index();

    // selects the <div> elements that are descendants of
    // a '.highlight-block' element:
    $('.highlight-block div')

    // finds the element that has an index in the collection
    // (not amongst its siblings) equal to the index of
    // the clicked <a> element:
    .eq(i)

    // adds the 'active' class-name to that <div>:
    .addClass('active')

    // selects the sibling elements of the <div>:
    .siblings()

    // and removes the 'active' class-name:
    .removeClass('active');
});

代码语言:javascript
复制
$('.links a').click(function() {
  var i = $(this).index();
  $('.highlight-block div.cb')
  .eq(i)
  .addClass('active')
  .siblings()
  .removeClass('active');
});
代码语言:javascript
复制
.links a {
  display: inline-block;
  border: 1px solid #000;
  margin: 0 0.25em;
}

.active {
  background-color: red;
}
代码语言:javascript
复制
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="links">
  <a href="#" class="lb block-1">Highlight Block 1</a>
  <a href="#" class="lb block-2">Highlight Block 2</a>
  <a href="#" class="lb block-3">Highlight Block 3</a>
  <a href="#" class="lb block-4">Highlight Block 4</a>
  <a href="#" class="lb block-5">Highlight Block 5</a>
  <a href="#" class="lb block-6">Highlight Block 6</a>
</div>

<div class="highlight-block">
  <div class="cb block-1 active">This is Block 1</div>
  <div class="cb block-2">This is Block 2</div>
  <div class="cb block-3">This is Block 3</div>
  <div class="cb block-4">This is Block 4</div>
  <div class="cb block-5">This is Block 5</div>
  <div class="cb block-6">This is Block 6</div>
</div>

外部JS Fiddle演示.

或者,如果您希望允许多个突出显示处于活动状态:

代码语言:javascript
复制
// selects the <a> element descendants of a '.links'
// element, and binds a click event-handler:
$('.links a').click(function () {

    // finds the index of the clicked <a>
    // amongst its sibling elements:
    var i = $(this).index();

    // finds the <div> elements that are descendants of
    // a '.highlight-block' element:
    $('.highlight-block div')

        // finds the <div> element whose index in the
        // collection is equal to the index of the <a>:
        .eq(i)

        // adds the 'active' class-name if it's not present,
        // removes the 'active' class-name if it is present:
        .toggleClass('active');
});

代码语言:javascript
复制
$('.links a').click(function () {
    var i = $(this).index();

    $('.highlight-block div')
        .eq(i)
        .toggleClass('active');
});
代码语言:javascript
复制
.links a {
  display: inline-block;
  border: 1px solid #000;
  margin: 0 0.25em;
}

.active {
  background-color: red;
}
代码语言:javascript
复制
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="links">
  <a href="#" class="lb block-1">Highlight Block 1</a>
  <a href="#" class="lb block-2">Highlight Block 2</a>
  <a href="#" class="lb block-3">Highlight Block 3</a>
  <a href="#" class="lb block-4">Highlight Block 4</a>
  <a href="#" class="lb block-5">Highlight Block 5</a>
  <a href="#" class="lb block-6">Highlight Block 6</a>
</div>

<div class="highlight-block">
  <div class="cb block-1 active">This is Block 1</div>
  <div class="cb block-2">This is Block 2</div>
  <div class="cb block-3">This is Block 3</div>
  <div class="cb block-4">This is Block 4</div>
  <div class="cb block-5">This is Block 5</div>
  <div class="cb block-6">This is Block 6</div>
</div>

外部JS Fiddle演示.

但是,如果您真的想使用相关的类名,那么我可以提供(但实际上并不推荐):

代码语言:javascript
复制
// binding a click event-handler to the <a> elements
// which are descendants of a '.links' element:
$('.links a').click(function () {

    // getting an Array-like list of class-names from the DOM node,
    // and using Function.prototype.call() to allow us to use the
    // Array.prototype.slice() in order to convert the Array-like
    // list into an actual Array:
    var allClasses = Array.prototype.slice.call(this.classList, 0),

    // filtering the Array of class-names with Array.prototype.filter():
        n = allClasses.filter(function (c) {
            // the first argument to the anonymous function ('c')
            // is the array-element of the array over which
            // we iterate with the filter() method.

            // if the following assessment evaluates to true
            // the array-element is returned; if it evaluates
            // to false it is discarded.

            // here we're using RegExp.prototype.test() to
            // keep only those array-elements (the String of
            // each class-name) which matches a pattern of a
            // String 'block-' followed by one or more ('+')
            // numbers '\d' and the end-of-string ('$'):
            return /block-\d+$/.test(c);

        // we then convert that Array to a string:
        }).toString()

        // and then find the string of digits ('\d'),
        // one or more ('+') that end the string ('$'):
        .match(/\d+$/);

    // because String.prototype.match() returns an Array
    // or null we first ensure that there is a returned
    // value ('if (n)'):
    if (n) {

        // selecting the <div> element with the class-name
        // of 'block-N' (where 'N' is the found-number):
        $('.highlight-block div.block-' + n)

            // adding the 'active' class-name to that <div>:
            .addClass('active')

            // selecting the sibling elements:
            .siblings()

            // removing the 'active' class-name:
            .removeClass('active');
    }
});

代码语言:javascript
复制
$('.links a').click(function() {
  var allClasses = Array.prototype.slice.call(this.classList, 0),
    n = allClasses.filter(function(c) {
      return /block-\d+$/.test(c);
    }).toString().match(/\d+$/);
  if (n) {
    $('.highlight-block div.block-' + n)
      .addClass('active')
      .siblings()
      .removeClass('active');
  }
});
代码语言:javascript
复制
.links a {
  display: inline-block;
  border: 1px solid #000;
  padding: 0.25em;
  margin: 0.2em;
  border-radius: 0.5em;
}
.active {
  background-color: red;
}
代码语言:javascript
复制
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="links"> <a href="#" class="lb block-1">Highlight Block 1</a>
  <a href="#" class="lb block-2">Highlight Block 2</a>
  <a href="#" class="lb block-3">Highlight Block 3</a>
  <a href="#" class="lb block-4">Highlight Block 4</a>
  <a href="#" class="lb block-5">Highlight Block 5</a>
  <a href="#" class="lb block-6">Highlight Block 6</a>

</div>
<div class="highlight-block">
  <div class="cb block-1 active">This is Block 1</div>
  <div class="cb block-2">This is Block 2</div>
  <div class="cb block-3">This is Block 3</div>
  <div class="cb block-4">This is Block 4</div>
  <div class="cb block-5">This is Block 5</div>
  <div class="cb block-6">This is Block 6</div>
</div>

外部JS Fiddle演示.

尽管简单地查找单击的<a>元素的相关类名并使用它(而不是上面的方法)更容易,但我忽略了类名'block-n'是相同的事实:

代码语言:javascript
复制
// finding the <a> element descendants of '.links' elements, and
// binding a click event-handler:
$('.links a').click(function () {

    // converting the Array-like list of class-names to an Array:
    var allClasses = Array.prototype.slice.call(this.classList, 0),

        // using the Array.prototype.filter() Array method
        // to find those array-elements (the class-names)
        // that have a string of 'block-' followed by a
        // numeric character ('\d') repeated one or more times
        // ('+') followed by the end of string ('$'):
        blockClass = allClasses.filter(function (c) {
            return /block-\d+$/.test(c);
        // converting the Array to a string:
        }).toString();

    // finding the <div> element descendants of a
    // '.highlight-block' element whose class-name
    // (the descendant <div>) is equal to the class
    // -name we found above from the clicked <a>:
    $('.highlight-block div.' + blockClass)

        // adding the 'active' class-name:
        .addClass('active')

        // finding the siblings of the <div>:
        .siblings()

        // removing the 'active' class-name:
        .removeClass('active');;
});

代码语言:javascript
复制
$('.links a').click(function() {
  var allClasses = Array.prototype.slice.call(this.classList, 0),
    blockClass = allClasses.filter(function(c) {
      return /block-\d+$/.test(c);
    }).toString();

  $('.highlight-block div.' + blockClass)
    .addClass('active')
    .siblings()
    .removeClass('active');;
});
代码语言:javascript
复制
.links a {
  display: inline-block;
  border: 1px solid #000;
  padding: 0.25em;
  margin: 0.2em;
  border-radius: 0.5em;
}
.active {
  background-color: red;
}
代码语言:javascript
复制
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="links"> <a href="#" class="lb block-1">Highlight Block 1</a>
  <a href="#" class="lb block-2">Highlight Block 2</a>
  <a href="#" class="lb block-3">Highlight Block 3</a>
  <a href="#" class="lb block-4">Highlight Block 4</a>
  <a href="#" class="lb block-5">Highlight Block 5</a>
  <a href="#" class="lb block-6">Highlight Block 6</a>

</div>
<div class="highlight-block">
  <div class="cb block-1 active">This is Block 1</div>
  <div class="cb block-2">This is Block 2</div>
  <div class="cb block-3">This is Block 3</div>
  <div class="cb block-4">This is Block 4</div>
  <div class="cb block-5">This is Block 5</div>
  <div class="cb block-6">This is Block 6</div>
</div>

外部JS Fiddle.

参考文献:

  • jQuery:
    • addClass()
    • click()
    • eq()
    • index()
    • removeClass()
    • siblings()
    • toggleClass()

票数 5
EN

Stack Overflow用户

发布于 2015-09-26 14:16:41

如果你想要困难的话:

代码语言:javascript
复制
$(document).ready(function () {
    $('.links a').click(function () {
        class_is=$(this).attr('class').match(/block-[0-9]/,'');

        $('.highlight-block div').each(function() {
         if($(this).attr('class').indexOf(class_is)!==-1) {
       $(this).toggleClass('active');
                $(this).siblings().removeClass('active');
         }
        })
    });
});

演示:http://jsfiddle.net/hurwpea3/4/

但是,我确实会推荐自定义数据属性方法,或者索引方法(如果html结构总是如所描述的那样)。

票数 0
EN

Stack Overflow用户

发布于 2015-09-26 14:17:38

将您是jQuery改为:

代码语言:javascript
复制
$(document).ready(function () {
    $('.links a').on('click', function () {
        className = $(this).attr('class').split(' ')[1];
        $('.highlight-block').find('.cb.' + className).toggleClass('active');
    });
});

这是一个小提琴

您还可以使用event对象中的pass对函数进行传递,并调用e.target而不是使用this,如下所示:

代码语言:javascript
复制
$(document).ready(function () {
    $('.links a').on('click', function (e) {
        className = $(e.target).attr('class').split(' ')[1];
        $('.highlight-block').find('.cb.' + className).toggleClass('active');
    });
});
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/32797997

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档