1

I created an ul dynamically, but when i used click function on the a tag inside the li tag, it only works after the second click. Here is my script

var uList;
    $(document).ready(function () {
        uList = $("#room");
        $("#btn").click(function () {
            appendLI();
        });

    });
    function test() {
        if ($("#room li").length > 0) {
            $("li .roomName").on("click", function () {
                alert($(this).text());
            });
        }
    }
    function appendLI() {
        var li = $("<li/>").appendTo(uList);
        var aaa = $("<a/>").prop("class", "roomName").prop("href", "javascript:test();").text("Google 1").appendTo(li);
    }

Here is my HTML

 <input type="text" autofocus/>
<ul id="room">
</ul>
<input type="button" id="btn" value="SET" />
2
  • First: var li = $("<li/>").appendTo(uList); You're trying to append to an undefined variable (uList) instead of an element. Second: using global variable is bad. Thirth: you shall define appendLI function before using. Commented Feb 14, 2017 at 3:40
  • Thank you for your answer, however, the uList is defined at the $(document).ready, why was is undefined? Can you explain why using global variable be considered bad? Commented Feb 14, 2017 at 4:03

1 Answer 1

4

The on click event isn't written right right;

function test() {
        if ($("#room li").length > 0) {
            $("#room").on("click", '.roomName', function () {
                alert($(this).text());
            });
        }
    }

I re-wrote your block of code here for you;

http://codepen.io/anon/pen/PWVmjJ

Sign up to request clarification or add additional context in comments.

3 Comments

thank you!! It works, however, may you point out where i was wrong? Why did it work on the 2nd time?
@KhoaĐỗ Event delegation. You were attaching events to li .roomName elements that don't exist yet. This snippet attaches the event to li, then checks if the original trigger was .roomName on click. This will keep working even if you add .roomName to li after binding the event listener.
@godfrzero thanks. Just found the document about event delegation learn.jquery.com/events/event-delegation

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.