javascript - JQuery 点击处理程序

标签 javascript jquery click handler

我正在创建一堆 div 并使用一个简单的函数通过引用的 js 文件插入缩略图。基本上我试图将点击处理程序分配给循环中的每个新 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,它工作得很好。不确定它是否是 z 排序的东西,因为可点击箭头 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);

    });
}​

因为您的主要问题是尝试将带有 jQ​​uery 语法的点击处理程序附加到 native JS DOM 元素。

关于javascript - JQuery 点击处理程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13793654/

相关文章:

javascript - 图像输入到 Canvas 和颜色选择器

c# - 在客户端上重置原始值时,DropDownList SelectedIndexChanged 不会运行

ios - Ionic2 iOS 转换阻止点击或点击一秒钟

c# - WPF按钮点击事件

javascript - 如何在 Javascript API 中完成安全认证

jquery - 如何使用 Google 托管的 jQuery UI 源?

javascript - 为什么 JS 增量简写不起作用

jQuery 使 addClass 可点击

php - 在 JSON 中传递 javascript 代码

javascript - Angular 404 不适用于 templateUrl 或 redirectTo