-1

这里我有 4 个 div 标签。它工作得很好,但我想知道我是否可以重构或连接对应于每个 div 的选择器。

$('.expand-one').click(function () {
$('.content-one').toggle();
});

$('.expand-two').click(function () {
$('.content-two').toggle();
});

$('.expand-three').click(function () {
$('.content-three').toggle();
});

$('.expand-four').click(function () {
$('.content-four').toggle();
});

<div class="expand-one>click to expand</div>
<div class="content-one">
<p>here is content</p>
</div>

<div class="expand-two>click to expand</div>
<div class="content-two">
<p>here is content</p>
</div>

<div class="expand-three>click to expand</div>
<div class="content-three">
<p>here is content</p>
</div>

<div class="expand-four>click to expand</div>
<div class="content-four">
<p>here is content</p>
</div>
4

3 回答 3

1

不是按类选择,而是通过 data-attr 进行选择,作为变量传递:

$('.expand').click(function() {
  $('.content[data-attr=' + $(this).data('attr') + ']').toggle();
});
.content {
  display: none
}

div:nth-of-type(1),
div:nth-of-type(2) {
  color: red
}

div:nth-of-type(3),
div:nth-of-type(4) {
  color: green
}

div:nth-of-type(5),
div:nth-of-type(6) {
  color: blue
}

div:nth-of-type(7),
div:nth-of-type(8) {
  color: orange
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="expand" data-attr="one">click to expand</div>
<div class="content" data-attr="one">
  <p>here is content</p>
</div>

<div class="expand" data-attr="two">click to expand</div>
<div class="content" data-attr="two">
  <p>here is content</p>
</div>

<div class="expand" data-attr="three">click to expand</div>
<div class="content" data-attr="three">
  <p>here is content</p>
</div>

<div class="expand" data-attr="four">click to expand</div>
<div class="content" data-attr="four">
  <p>here is content</p>
</div>

于 2019-12-26T22:19:24.973 回答
0

这个怎么样

$('.expand-one, .expand-two, .expand-three, .expand-four').click(function (e) {
  var contentIndex = e.target.className.substr(7, e.target.className.length);//mind that 7 is a fixed number in case it is going to be ".expand-" for every case
  $('.content-' + contentIndex ).toggle();
});
于 2019-12-26T20:33:12.053 回答
0

我同意使用通用类的建议。所以是这样的:

HTML

<div class="expand-one expand-header">...</div>
<div class="content-one expand-content">...</div>
<!-- and so on -->

JavaScript

$('.expand-header').click(function () {
    $(this).next('.expand-content').toggle();
}

但是,如果由于某种原因您不能使用公共类,则可能会使用“类开头”选择器语法,因此:

// Handle click for each element whose class name beings with "expand-"
$('[class^="expand-"]').click(function () {
    // Toggle the "next" element with class starts with "content-"
    $(this).next('[class^="content-"]').toggle();
}
于 2019-12-26T21:49:26.947 回答