简体   繁体   中英

jQuery select data attribute and hide

I have a button which has an ID, on click of the button I need to match the ID of the button with the documents data-id attribute and then add a class to the respective element.

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> 

Your .hidden class is not defined, so the class is added, but no css is applied.

I've only added the .hidden class

 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> 

Well to modify a bit you can use template literals to overcome the dirtiness of string concat,its just a add on

 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> <!-- Latest compiled and minified CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css"> <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> <style> .hidden{ //attribute you want to add } </style> 

hide() method hides the selected elements in jQuery :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM