你能点击'jQuery中加载的内容吗? [英] Can you 'click' loaded content in jQuery?

查看:68
本文介绍了你能点击'jQuery中加载的内容吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个页面,其中示例div可以点击,因为它将在下面。

I am trying to create a page where the example div is clickable, as it would be below.

但是我试图这样做,如果用户点击徽标,它将使用加载重新加载原始内容。

However I'm trying to make it so if the user clicks the logo it will reload the original content using load.

发生此加载后,可以点击加载的< div ID = 例如 > ?我正在尝试此操作,当点击file.php中已加载的< div id =example> 时,它无法提醒

After this load has occurred is it possible to 'click' a loaded <div id="example">? I'm trying this at the moment and it fails to alert when clicking the loaded <div id="example"> that is in file.php

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Example</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {

    $("#example").click(function(){
        alert("You clicked me!");
    });

    $("#logo").click(function(){
        $("#main").load("file.php");
    });
});
</script>
    </head>

<body>
    <img id="logo" src="404.gif" />

    <div id="main">
        <div id="example">This is content.</div>
    </div>
</body>
</html>

file.php包含

file.php contains

<div id="example">This is loaded content that can't be clicked?</div>


推荐答案

问题



问题是 .click()仅将事件绑定到当时存在于DOM中的元素。这意味着当你向页面添加一个新元素时,它不会绑定一个事件处理程序。

Problem

The problem is that .click() only binds events to elements that exist in the DOM at that moment in time. Meaning that when you add a new element to the page, it will not have an event handler bound to it.

如果您使用的是jQuery 1.7+,而不是在代码中使用 .click(),请使用 .on()而不是。

If you're using jQuery 1.7+, rather than using .click() in your code use .on() instead.

$("#main").on('click', '#example', function(){
    alert("You clicked me!");
});

...或者使用旧版本的jQuery使用 .live()而不是:

...or with older versions of jQuery use .live() instead:

$("#example").live('click', function(){
    alert("You clicked me!");
});

这将确保添加到DOM的新元素也会将事件处理程序绑定到它们。

This will ensure that new elements added to the DOM will get the event handler bound to them also.

这篇关于你能点击'jQuery中加载的内容吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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