【问题标题】:Remove the need for a second .click within a script无需在脚本中再次单击 .click
【发布时间】:2015-05-07 09:15:28
【问题描述】:

我正在使用与类似问题类似的设置,其中我有一排内联块,单击任何块时都会在该行下方创建一个内容框。

Add a div below inline-block wrapped row

不同之处在于,在单击块时,我通过 AJAX 加载了数据,使用链接问题中提供的小提琴,我的功能正常工作,除了我必须按两次块才能运行这两个功能。

第一次点击:通过 AJAX 加载数据

第二次点击:在一行块下面创建内容框

如果您查看我下面的代码,您会看到评论“点击下方是我要删除的事件”

您可以看到“gameListing Click Event”的副本,基本上我试图将其链接到第一个 Click Event,所以我只需要单击一次。

我希望这是有道理的,如果需要,我很乐意扩展我的问题。

// -------------- MAIN CLICK FUNCTION --------------
$('.gameListing').click(function(){

    $('.gameListing').removeClass('active');
    $(this).addClass('active');

    var id = $(this).attr('data-id');
    var url = "http://localhost:8888/projects/superfreerespo/" + id + "?json=get_category_posts&slug=games";

    call_ajax(url);
});


// -------------- GET PREV / NEXT ITEMS --------------
$('.prev').click(function(){
    var $current = $('.gameListing.active');
    $current.removeClass('active')
    var postNumber = parseInt($current.attr('data-count'));
    var nextPost = (postNumber - 1);
    $("[data-count='"+nextPost+"']").trigger("click");
});

$('.next').click(function(){
    var $current = $('.gameListing.active');
    $current.removeClass('active')
    var postNumber = parseInt($current.attr('data-count'));
    var nextPost = (postNumber + 1);
    $("[data-count='"+nextPost+"']").trigger("click");
});


// -------------- MAIN AJAX FUNCTION CALL --------------
function call_ajax(url) {

    $.ajax( {
            url: url,
            method: "GET",
            data: {json:  1},
            dataType: "JSON"
     })

        .done(function( data ) {

        // LOAD GAME INFORMATION
        $("#game-name").html(data.post.title);
        $("#game-reels").html(data.post.custom_fields.reels);
        $("#game-paylines").html(data.post.custom_fields.paylines);
        $("#game-minBet").html(data.post.custom_fields.min_bet);
        $("#game-maxBet").html(data.post.custom_fields.max_bet);
        $("#game-jackpot").html(data.post.custom_fields.jackpot);
        $("#game-info").html(data.post.custom_fields.game_info);

        // LOAD GAME PROVIDERS
        var provSource = new String(data.post.custom_fields.game_name);
                provSource = provSource.replace(/ /g,"-");
                $("#game_provs").load("http://localhost:8888/projects/superfreerespo/" + provSource + "/ .gameBox-Ops");

        // LOAD GAME THUMBNALS
        var gameThumbSrc = new String(data.post.custom_fields.game_name);
        gameThumbSrc = gameThumbSrc.replace(/ /g,'');

        $('#gameBoxGallery').html('');
            for(i = 0;  i<= 2; i++){
                            image = '<img src="<?php bloginfo('template_directory'); ?>/images/games/screenshots/' + gameThumbSrc + '-' + i + '.jpg" class="gameThumb">'
                            $('#gameBoxGallery').append(image);
        };

        // ZOOM FIRST THUMBNAIL
        $('#gameBox-Screenshot').html('');
            image = '<img src="<?php bloginfo('template_directory'); ?>/images/games/screenshots/' + gameThumbSrc + '-0' + '.jpg" id="gameScreenshot">'
        $('#gameBox-Screenshot').append(image);

        })  



// -------------- CREATE CONTENT BOX  --------------

        function placeAfter($block) {
            $block.after($('#gameBox'));
        }

        var $chosen = null;


        // -------------- THIS ON CLICK BELOW IS THE EVENT I AM TRYING TO REMOVE --------------
        $('.gameListing').on('click', function() {


            $chosen = $(this);
            $('#gameBox').css('display','inline-block');
            $('#gameBox').slideDown( 3000 );


            var top = $(this).offset().top;
            var $blocks = $(this).nextAll('.gameListing');
            if ($blocks.length == 0) {
                placeAfter($(this));
                return false;
            }
            $blocks.each(function(i, j) {
                if($(this).offset().top != top) {
                    placeAfter($(this).prev('.gameListing'));
                    return false;
                } else if ((i + 1) == $blocks.length) {
                    placeAfter($(this));
                    return false;
                }
         });

        $('html, body').animate({ scrollTop: $(this).offset().top - 40}, 600);
});
}

这是原始小提琴的链接:http://jsfiddle.net/SYJaj/7/

【问题讨论】:

  • 首先 .. 如果你使用 .on 监听器,我不明白为什么你在 call_ajax 函数中有 jquery.event.on
  • 请原谅任何菜鸟的错误,我边走边学
  • 我只是问,因为我不明白 :) 如果你 .on fnc 放在 call_ajax 外面,什么也没发生?
  • 在.done 之后你不见了; |注意 $ 它是 jquery 的东西 .. 从 fnc placeAfter 中删除 $,因为您传递对象并使用此对象

标签: javascript jquery


【解决方案1】:

好吧,您可以将附加框功能从新的单击处理程序和call_ajax 函数中移出。所以我这样做并做到了,以便在您的 AJAX 调用完成时调用该函数。因为你需要this(被点击的元素),你也需要传递它。

您在点击处理程序中设置了一个新的点击处理程序,所以这就是您的问题发生的原因。

我没有重新构建你的代码,而是这样做了......

试试看:

// -------------- MAIN CLICK FUNCTION --------------
$('.gameListing').click(function () {

    $('.gameListing').removeClass('active');
    $(this).addClass('active');

    var id = $(this).attr('data-id');
    var url = "http://localhost:8888/projects/superfreerespo/" + id + "?json=get_category_posts&slug=games";

    // Pass the url and the clicked element
    call_ajax(url, this);
});


// -------------- GET PREV / NEXT ITEMS --------------
$('.prev').click(function () {
    var $current = $('.gameListing.active');
    $current.removeClass('active')
    var postNumber = parseInt($current.attr('data-count'));
    var nextPost = (postNumber - 1);
    $("[data-count='" + nextPost + "']").trigger("click");
});

$('.next').click(function () {
    var $current = $('.gameListing.active');
    $current.removeClass('active')
    var postNumber = parseInt($current.attr('data-count'));
    var nextPost = (postNumber + 1);
    $("[data-count='" + nextPost + "']").trigger("click");
});


// -------------- MAIN AJAX FUNCTION CALL --------------
function call_ajax(url, elem) {

    $.ajax({
        url: url,
        method: "GET",
        data: {
            json: 1
        },
        dataType: "JSON"
    })
    .done(function (data) {

        // Append the box
        appendBox(elem);

        // LOAD GAME INFORMATION
        $("#game-name").html(data.post.title);
        $("#game-reels").html(data.post.custom_fields.reels);
        $("#game-paylines").html(data.post.custom_fields.paylines);
        $("#game-minBet").html(data.post.custom_fields.min_bet);
        $("#game-maxBet").html(data.post.custom_fields.max_bet);
        $("#game-jackpot").html(data.post.custom_fields.jackpot);
        $("#game-info").html(data.post.custom_fields.game_info);

        // LOAD GAME PROVIDERS
        var provSource = new String(data.post.custom_fields.game_name);
        provSource = provSource.replace(/ /g, "-");
        $("#game_provs").load("http://localhost:8888/projects/superfreerespo/" + provSource + "/ .gameBox-Ops");

        // LOAD GAME THUMBNALS
        var gameThumbSrc = new String(data.post.custom_fields.game_name);
        gameThumbSrc = gameThumbSrc.replace(/ /g, '');

        $('#gameBoxGallery').html('');
        for (i = 0; i <= 2; i++) {
            image = '<img src="<?php bloginfo('
            template_directory '); ?>/images/games/screenshots/' + gameThumbSrc + '-' + i + '.jpg" class="gameThumb">'
            $('#gameBoxGallery').append(image);
        };

        // ZOOM FIRST THUMBNAIL
        $('#gameBox-Screenshot').html('');
        image = '<img src="<?php bloginfo('
        template_directory '); ?>/images/games/screenshots/' + gameThumbSrc + '-0' + '.jpg" id="gameScreenshot">'
        $('#gameBox-Screenshot').append(image);

    });
}

// Move the box-appending code outside of the AJAX call,
// and outside of a new click event
function appendBox(elem) {
    var $chosen = $(elem),
        $gameBox = $('#gameBox'),
        top = $chosen.offset().top,
        $blocks = $chosen.nextAll('.gameListing');
    if($chosen.attr('data-id') === $gameBox.attr('data-id')) {
        $gameBox.stop().slideUp(3000, function () {
            $(this).css('display', 'none');
        });
        $gameBox.attr('data-id', '');
    } else {
        $gameBox.slideDown(3000, function () {
            $(this).css('display', 'inline-block');
        });
        $gameBox.attr('data-id', $chosen.attr('data-id'));
    }
    function placeAfter($block) {
        $block.after($gameBox);
    }
    if ($blocks.length == 0) {
        placeAfter($chosen);
        return false;
    }

    $blocks.each(function (i, j) {
        if ($(this).offset().top != top) {
            placeAfter($(this).prev('.gameListing'));
            return false;
        } else if ((i + 1) == $blocks.length) {
            placeAfter($(this));
            return false;
        }
    });

    $('html, body').animate({
        scrollTop: $chosen.offset().top - 40
    }, 600);
}

【讨论】:

  • 这太棒了,正是我想要实现的目标。但是没有加载 ajax 内容...
  • 嗯,所以你点击元素,框追加,但框中的内容没有更新?检查done 函数内部的代码,并记录data 以查看是否有任何信息。另外,打开您的 Web 控制台,看看是否出现任何错误。
  • Console 中出现的唯一错误是 Uncaught TypeError: Cannot read property 'top' of undefined
  • 好的,所以我删除了 $('html, body').animate({ scrollTop: $(this).offset().top - 40 }, 600);现在似乎一切正常
  • 非常感谢您,不能强调它有多大帮助。我的下一个目标是检测 GameBox 的打开/关闭状态,并能够在第二次点击时再次关闭它,对此有何建议?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-04
  • 1970-01-01
  • 1970-01-01
  • 2017-09-10
  • 2017-10-29
  • 1970-01-01
相关资源
最近更新 更多