G
G
GennadyPHP2018-07-12 16:44:00
JavaScript
GennadyPHP, 2018-07-12 16:44:00

Why is the element created but not rendered by JS in any way?

There is a code that creates a block

var buttonid = 0; // глобальная переменная где-то вначале 

$(document).ready(function(){
    $("#addbutton").click(function(){
        $(".block").append('<span>Кнопка '+buttonid+'</span>');
        buttonid++;
    })

    $("span").click(function(){
         alert($(this).text()); // не возвращает нужного результата.
    })
})

Some code that should create elements, and then freely access them. But in fact, if you create an HTML span element in advance, then it is drawn without problems, but if it is created by JS, then nothing happens. Thanks

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry, 2018-07-12
@GennadyPHP

$(document).on("span", 'click', function() {
         alert($(this).text()); // не возвращает нужного результата.
});

But this will bind to all spans, I think you know what to do next.

V
VoidVolker, 2018-07-12
@VoidVolker

var buttonid = 0; // глобальная переменная где-то вначале 

$(document).ready(function(){
    $("#addbutton").click(function(){
        var item = $('<span>Кнопка '+buttonid+'</span>');
        $(".block").append(item);
        buttonid++;

        item.click(function(){
             alert($(this).text());
        })
    });
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question