Permanent display (hide / show) for dynamically created DOM elements?

I have a set of DOM elements that I want to show only when the checkbox is set by the user. All these elements have a common class and are initially hidden:

 .spec { display:none; }

In the checkbox click handler, I initially had the following: which worked fine for existing elements. However, tables are dynamically generated via AJAX, and when new items are added with the class "spec", they are not displayed when the checkbox is selected.

// Basic jQuery show/hide
if (btn.checked)
    $('.spec').show();
else
    $('.spec').hide();

Since in my case this is in the same JS module, I could always just re-execute this code after adding it to the DOM. But overall this may not be true, so my question is:

What is the normal jQuery way to solve this problem?

show/hide jQuery element.style, , jQuery, stylesheet, , , , .

var nval = btn.checked ? '' : 'none';
$.styleSheet('.spec', 'display', nval );
+3
5

<body> ( ) , jQuery.

CSS

body.spec_is_hidden .spec {
  display: none;
}

JS:

if (btn.checked)
    $('body').addClass('spec_is_hidden');
else
    $('body').removeClass('spec_is_hidden');
+3

, . , DOM, , .

0

2 : 1) live , , : `$ ('a.special'). Live ("click", function() {...});

2) callback load. : $('p .special').load('x.html', {}, function(){ //search for new element and bind them new function. ...

;)

0

:)

, $(".spec").show().

, ? , - , , . , CSS.

0

, , btn . ( ) , , . change - , . DOM, :

$(btn).change(function(){
  $('.spec').toggle();
});

toggle, display:hidden display:block/inline . , :

$(btn).change(function(){
  $('.spec')[$(this).val() ? 'show' : 'hide']();
});
-1

Source: https://habr.com/ru/post/1721135/


All Articles