使用jQuery访问动态创建的项目? [英] Access dynamically created items using jQuery?

查看:65
本文介绍了使用jQuery访问动态创建的项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个页面,其中一些html动态地添加到页面中.

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

这是创建的html和javascript:

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>

在Firebug控制台中,我看到一条错误消息:

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

TypeError:$(#btn")为空

TypeError: $("#btn") is null

jQuery最初是在页面上加载的.

jQuery is being loaded on the page initially.

我在做什么错了?

推荐答案

您必须将on()(或on()方法中定义的事件)绑定到DOM中存在的元素, jQuery已运行.通常在$(document).ready()或类似版本上.

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.

绑定到最接近的元素,该元素将在页面加载/DOM准备就绪时添加到DOM中存在的$('#btn')元素.

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

假设您正在将$('#btn')加载到#container div中(例如),得到:

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>

然后使用:

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

这篇关于使用jQuery访问动态创建的项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆