开发者

one element, one event, one alert, one click, 4 messages

开发者 https://www.devze.com 2023-02-25 06:05 出处:网络
HTML: <html> <head> <meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">

HTML:

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title></title>
        <link type="text/css" href="galerina.css" rel="stylesheet"/>
    </head>
    <body>
        <div class="galerina">
            <img class="img1" src="images/1.jpg" alt=""/>
            <img class="img2" src="images/2.jpg" alt=""/>
            <img class="img3" src="images/3.jpg" alt=""/>
            <img class="img4" src="images/4.jpg" alt=""/>
            <p/>
        </div>

        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
        <script type="text/javascript" src="galerina.js"></script>
    </body>
</html>

CSS:

div.galerina{
    max-width: 500px;
    position: relative;
}

div.galerina img{
    margin: auto;
    display: none;
    opacity: 0;
}

div.galerina img.galerina1, div.galerina img.bullet{
    display: block;
    opacity: 1;
}

JS:

/* Find each div with class galerina */
$("div.galerina").each(function(){
    var gal=$(this);
    var size=$(gal).children("img").size();
    var i=0;
    /* Find each img tag inside the div */
    $(gal).children("img").each(function(){
        var img=$(this);
        /* Append an image to the gal and show an alert */
        $(gal).append("<img src='images/bullet.png'/>").click(function(){
            alert('test');
        });
    });
});

clicking on bu开发者_C百科llet makes 4 test alerts popup??


I think you're confused about what $(gal).append() returns, it returns $(gal) not the thing that was appended. So, when you say this:

$(gal).append("<img src='images/bullet.png'/>").click(function() { /* ... */ });

You are adding a click handler to $(gal) and you do that once every time you go through the loop so you end up with four identical click handlers. I think you want something more like this:

var $img = $('<img src="images/bullet.png"/>');
$img.click(function() { alert('test'); });
$(gal).append($img);

That will put the click handler on the appended image rather than on $(gal).


It's because you've said that alert('test') should be called for each of the img children in div.galerina. I've edited the formatting of your question to help you see why this is the case.


By using event delegation you can avoid the headache of binding a click handler to each image:

$("div.galerina").delegate("img", "click", function() {
    alert("test");
});

You can try it here.

Reference:

  • http://api.jquery.com/delegate/
0

精彩评论

暂无评论...
验证码 换一张
取 消