Div选择器不在函数定义中发送调试器

时间:2012-01-24 06:57:09

标签: javascript jquery asp.net

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default3.aspx.cs" Inherits="Default3" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script language="javascript" type="text/javascript" src="jquery-1.7.1.js"></script>
    <script language="javascript" type="text/javascript">
        $('#clickme').click(function () {
            alert('Entered'); $('#book').animate({
                opacity: 0.25, left: '+=50', height: 'toggle'
            }, 5000, function () {
                // Animation    complete. 
            });
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div id="clickme" class="hiii">
        Click here
    </div>
    <img id="book" src="Chrysanthemum.jpg" alt="" width="10" height="12" style="position: relative;
        left: 10px;" />
    </form>
</body>
</html>

3 个答案:

答案 0 :(得分:2)

你需要将你的函数包装在$(document).ready函数中以确保DOM可用,即

$(document).ready(function(){

  $('.hiii').click(function () { 
     //.. your code
   });

});

这会解释这个丢失的处理程序。我认为这与SO question相同。

答案 1 :(得分:1)

我猜你在点击事件时没有呈现div 你应该根据你的JQuery版本使用JQuery on \ live \ delegate函数:

$(selector).live(events, data, handler);                // jQuery 1.3+
$(document).delegate(selector, events, data, handler);  // jQuery 1.4.3+
$(document).on(events, selector, data, handler);        // jQuery 1.7+ 

on版本(您引用了JQuery1.7.1):

$("body").on("click", ".hiii", function(){
    debugger;
    $('#book').animate({
        opacity: 0.25,
        left: '+=50',
        height: 'toggle'
    }, 5000, function () {
        // Animation complete.
    });       
);

顺便说一句,<div>有一个id和一个类,按id选择更有效率。您可能希望将选择器从.hiii更改为#clickme


根据您的评论更新: 您遇到了问题,因为您尝试将事件侦听器附加到尚未呈现的元素。修正版:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script language="javascript" type="text/javascript" src="jquery-1.7.1.js"></script>
    <script language="javascript" type="text/javascript">
function doAnimation (){
        $('#clickme').click(function () {
            alert('Entered'); $('#book').animate({
                opacity: 0.25, left: '+=50', height: 'toggle'
            }, 5000, function () {
                // Animation    complete. 
            });
        });
};
$(doAnimation);
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div id="clickme" class="hiii">
        Click here
    </div>
    <img id="book" src="Chrysanthemum.jpg" alt="" width="10" height="12" style="position: relative;
        left: 10px;" />
    </form>
</body>
</html>

JQuery DOM ready article

答案 2 :(得分:0)

重建项目将解决问题