Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have a page where some html is being dynamically added to the page.

This is the html and javascript that is created:

<div>
    <script type="text/javascript" language="javascript">
        $('#btn').click(function() {
            alert("Hello");
        });
    </script>

    <a id="btn">Button</a>
</div>

Looking in my Firebug console, I get an error that says:

TypeError: $("#btn") is null

jQuery is being loaded on the page initially.

What am I doing wrong here?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
278 views
Welcome To Ask or Share your Answers For Others

1 Answer

You have to bind on() (or the events defined within the on() method, to an element that exists in the DOM at the point at which the jQuery was run. Usually this is on $(document).ready() or similar.

Bind to the closest element in which the $('#btn') element will be appended that exists in the DOM on page-load/DOM ready.

Assuming that you're loading the $('#btn') into the #container div (for example), to give:

<div id="container">
    <div>
        <a href="#" id="btn">Button text</a>
    </div>
</div>

Then use:

$('#container').on('click', '#btn', function(){
    alert('Button clicked!');
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...