jQuery选择数据属性并隐藏

时间:2019-01-28 09:13:46

标签: javascript jquery

我有一个带有ID的按钮,单击按钮时,我需要将按钮的ID与documents data-id属性进行匹配,然后将一个类添加到各个元素中。

JS Fiddle

this.$('.add-resource').click(function() {
  var testId = $(this).attr('id');
  alert(testId);
  $('#layoutCanvas').find("[data-id='" + testId + "']").addClass('hidden');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a class="btn btn-primary add-resource" id="567">Button</a>
<div id="layoutCanvas">
  <div data-id="567">
    Test 1
  </div>

  <div data-id="235">
    Test 2
  </div>
</div>

3 个答案:

答案 0 :(得分:4)

您的.hidden类未定义,因此添加了该类,但未应用任何CSS。

我只添加了.hidden

this.$('.add-resource').click(function () {
     var testId = $(this).attr('id');
     //alert(testId);
     $('#layoutCanvas').find("[data-id='" + testId + "']").addClass('hidden');
});
.hidden {
  display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="btn btn-primary add-resource" id="567">Button</button>


<div id="layoutCanvas">
    <div data-id="567">
        Test 1
    </div>
    
    <div data-id="235">
        Test 2
    </div>
</div>

答案 1 :(得分:1)

可以稍微修改一下,您可以使用模板文字来克服字符串concat的肮脏性,只是添加

input[type="number"] {
  -webkit-appearance: textfield;
  -moz-appearance: textfield;
  appearance: textfield;
}

input[type=number]::-webkit-inner-spin-button,
input[type=number]::-webkit-outer-spin-button {
  -webkit-appearance: none;
}

.number-input {
  border: 0;
  display: inline-flex;
}

.number-input,
.number-input * {
  box-sizing: border-box;
}

.number-input button {
  outline:none;
  -webkit-appearance: none;
  background-color: transparent;
  border: none;
  align-items: center;
  justify-content: center;
  width: 3rem;
  height: 3rem;
  cursor: pointer;
  margin: 0;
  position: relative;
  box-shadow: 0px 0px 1px #474747;
    border-radius: 50%;
}

.number-input button:before,
.number-input button:after {
  display: inline-block;
  position: absolute;
  content: '';
  width: 1rem;
  height: 2px;
  background-color: #212121;
  transform: translate(-50%, -50%);
}
.number-input button.plus:after {
  transform: translate(-50%, -50%) rotate(90deg);
}

.number-input input[type=number] {
  font-family: sans-serif;
  max-width: 5rem;
  padding: .5rem;
  border: none;
  border-width: 0 2px;
  font-size: 2rem;
  height: 3rem;
  font-weight: bold;
  text-align: center;
  color:#9be3df;
}
<div class="number-input">
  <button onclick="this.parentNode.querySelector('input[type=number]').stepDown()" ></button>
  <input class="quantity" min="0" name="quantity" value="1" type="number">
  <button onclick="this.parentNode.querySelector('input[type=number]').stepUp()" class="plus"></button>
</div>

答案 2 :(得分:0)

hide()方法在jQuery中隐藏所选元素:

this.$('.add-resource').click(function () {
     var testId = $(this).attr('id');
     alert(testId);
     $('#layoutCanvas').find("[data-id='" + testId + "']").hide();
});