使用jquery插入HTML

时间:2013-06-06 14:04:47

标签: javascript jquery ajax

我有两段代码,首先我有我的代码,用包含的关闭按钮切换打开div:

http://jsfiddle.net/spadez/uhEgG/27/

$(document).ready(function () {


    $('#country').click(function () {
        $("#country_slide").slideToggle();
    });

    $('#close').click(function (e) {
        e.preventDefault();
        $('#country_slide').slideToggle();
    });

});

然后我还有我的Ajax代码,它被设计为在打开div时触发:

$(function () {
    $('#country_link').on('click', function () {
        $.ajax({
            type: 'GET',
            dataType: 'html',
            url: '/ajax/test.html',
            timeout: 5000,
            beforeSend: function () {
                $('.loader').show();
            },
            success: function (data, textStatus) {
                $("#country_slide").html(data);
                alert('request successful');
            },
            error: function (xhr, textStatus, errorThrown) {
//                $("#country_slide").hide('fast');
//                alert('request failed');                
            },
            complete: function () {
                $('.loader').hide();
            },
        });
        return false;
    });
});

我现在所困扰的是,如何在打开div时仅执行ajax?因为我正在使用切换和关闭按钮,所以似乎很难弄清楚点击正在做什么,无论是打开它还是关闭它。

我想我的选择是有某种标志或者有一些“if”代码,所以如果class等于.hidden那么就不要执行了。我无法集成这些解决方案中的任何一个,我不确定它们中的任何一个是否是实现这一目标的正确方法。

如果有什么可以提供一些建议,我们将非常感激。

3 个答案:

答案 0 :(得分:1)

if($("#country_slide").is(":visible")) 
  //call ajax    

答案 1 :(得分:1)

将支票作为幻灯片功能的一部分包括在内:

$("#country_slide").slideToggle(function() {
    if ($(this).is(":visible")) {
        alert("im visible!");
    }
});

演示:http://jsfiddle.net/tymeJV/uhEgG/28/

答案 2 :(得分:1)

此代码将data添加到元素中,以检查下次单击它时是否已加载。

目前我无法对其进行测试,因此可能包含错误。

$(function () {
    $('#country_link').on('click', function (e) {
        // Prevent from following the link, if there is some sort of error in
        // the code before 'return false' it would still follow the link.
        e.preventDefault();

        // Get $link because 'this' is something else in the ajax request.
        var $link = $(this);
        // Exit if the data is loaded already
        if ($link.data('loaded') === true)
            return false;

        $.ajax({
            type: 'GET',
            dataType: 'html',
            url: '/ajax/test.html',
            timeout: 5000,
            beforeSend: function () {
                $('.loader').show();
            },
            success: function (data, textStatus) {
                $("#country_slide").html(data);
                alert('request successful');
                // If successful, bind 'loaded' in the data
                $link.data('loaded', true)
            },
            error: function (xhr, textStatus, errorThrown) {
//                $("#country_slide").hide('fast');
//                alert('request failed');
            },
            complete: function () {
                $('.loader').hide();
            },
        });
    });
});