JQuery replaces div stops responding to mouseclick

I am trying to replace a value in a drop down list. Replacing works fine (after using this great community), but then the slide function stops working. I cannot find any errors, so I ask, can this be related to how jQuery and javaScript work? Are the elements "mapped" to the DOM at boot time, and if so; will it mean that replacing a div with another div will cause jQuery to lose track divs?

I use this code to check if a div is pressed:

$(document).ready(function () {

    $('.button_slide').click(function () {
        var num = $(this).attr('rel');
        $('div.content_slide:not(.' + num + ') ').slideUp(400);
        $('div.' + num).slideToggle(400);
    });
    return false;
});

This is the div:

<div class="button_slide" rel="slide1">Alts:</div>
<div class="content_slide slide1">
  <input id="Button1" rel="slide1" class="button_vertical click_button" type="button" value="2" size="10px" />
  <input id="Button2" rel="slide1" class="button_vertical click_button" type="button" value="3" />                                                    
</div>

This is jQuery that falls into the field:

        $(function () {

            $('.click_button').click(function () {

                var num = $(this).attr('rel');

                $('.button_slide[rel="' + num + '"]').replaceWith("<div class='button_slide' rel='" + num + "' >" + $(this).val() + "</div>");
                $('div.content_slide').slideUp(600);
            });
        });

I pull my hair on it and jQuery is not my forte ... How would you solve this?

+3
source share
3

jQuery bind (, click) . , , , .

- delegate. Javascript, , , , DOM, . (, document.body , HTML) :

$(document).ready(function () {
    $(document.body).delegate('.button_slide','click', function () {
        var num = $(this).attr('rel');
        $('div.content_slide:not(.' + num + ') ').slideUp(400);
        $('div.' + num).slideToggle(400);
    });
    return false;
});
+1

click (), jQuery.
.

.live, , , , .

:

$('.click_button').live('click', function() {
    ...
});
+6

Try the following:

$('.click_button').live('click', function() {
   ... your code... 
});

The delegate is better, but since you say jQuery is not your forte, we won’t go there now.

Basically, what happens is that the new DIVs do not exist at the time the event handler is bound. Live () binds an event handler for all existing and future divs, binding one event handler to the document and looking for matches during the event.

Hope this helps.

+1
source

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


All Articles