繁体   English   中英

JQuery Click Handler

[英]JQuery Click Handler

我正在使用一个简单的函数创建一堆div并通过引用的js文件插入缩略图。 基本上我正在尝试将click处理程序分配给循环中的每个新div ,但由于语法原因,它无法正常工作。

这是我的代码(更新)......

function makethumbs() {

    for (var i = 0; i < 14; i++) {

        var backgroundUrl = script_vars + "/images/gallery/thumbs/g" + (i+1) + ".jpg",
            newdiv = $('<div />', {id: 'thumbnail'+i, width: 145, height: 84});
            newdiv.css({display:'inline', 
                        float:'left', 
                        margin:'2px 2px 0 0', 
                        color:'#000', 
                        fontSize:'18px', 
                        zIndex:0,
                        html:'P',
                        background: 'url(' + backgroundUrl + ')'
                       });
            newdiv.click(function() {
                $(this).stop(true, true).fadeTo('slow', 0);
            });

        $('#thumbholder').append(newdiv);
    }

    $('#arrowright').click(function() {
        var L = $('#thumbholder'),
            margL = parseInt(L.css('marginLeft'), 10),
            newMarg = (margL - 147) + 'px',
            anim = {opacity: 1};
            anim["marginLeft"] = newMarg;
        $('#thumbholder').stop(true, true).animate(anim, 400);

    });
}

对于#arrowright来说,还有一个额外的点击处理程序。 不确定它的az排序事物是否是可点击的箭头div是在容器内部,如果有意义的话,它会覆盖缩略图div

为什么不继续使用jQuery?

function makethumbs() {
    for (var i = 0; i < 14; i++) {

        var backgroundUrl = script_vars + "/images/gallery/thumbs/g" + (i+1) + ".jpg",
            newdiv = $('<div />', {id: 'thumbnail'+i, width: 145, height: 84});
            newdiv.css({display:'inline', 
                        float:'left', 
                        margin:'2px 2px 0 0', 
                        color:'#000', 
                        fontSize:'18px', 
                        zIndex:0,
                        html:'P',
                        background: 'url(' + backgroundUrl + ')'
                       });
            newdiv.click(function() {
                $(this).stop(true, true).fadeTo('slow', 0);
            });

        $('#thumbholder').append(newdiv);
    }

    $('#arrowright').click(function() {
        var L = $('#thumbholder'),
            margL = parseInt(L.css('marginLeft'), 10),
            newMarg = (margL - 147) + 'px',
            anim = {opacity: 1};
            anim["marginLeft"] = newMarg;
        $('#thumbholder').stop(true, true).animate(anim, 400);

    });
}​

因为您的主要问题是尝试将带有jQuery语法的单击处理程序附加到本机JS DOM元素。

newDiv.click更改为$(newDiv).click newDiv.click ,因为您似乎正在使用jQuery; 但是如果你想继续使用原生的javascript,你可以为元素设置一个事件,如下所示:

newDiv.addEventListener('click',function(){
//you code here
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM