找到/最接近有困难

时间:2012-05-29 09:34:09

标签: jquery jquery-ui jquery-selectors

更新1:

我是否遇到此问题,因为我在.BC1可以使用之前删除了get_firm_summary();

原始问题:

我已经重新开始这个问题,因为它结构不合理并且造成了很多混乱。

在开始之前,我想指出我正在使用jQuery 1.4

我有一个函数,我在某些HTML中动态创建span标记,span标记看起来像这样:

<span class='BC1'>some text here</span>

插入.BC1之前的HTML如下所示:

<div class="portlet_10">
    <div class="portlet_header_10"></div>
    <div class="portlet_sub_header_10">this is where the span gets inserted</div>
    <div class="portlet_content_10">this is the bit which should get cleared and appended with new data</div>
    <div class="portlet_footer_10"></div>
<div>

在插入.BC1之后看起来像这样:

<div class="portlet_10">
    <div class="portlet_header_10"></div>
    <div class="portlet_sub_header_10"><span class="BC1">some text here</span></div>
    <div class="portlet_content_10">this is the bit which should get cleared and appended with new data</div>
    <div class="portlet_footer_10"></div>
<div>

然后我为此click标记发送了.BC1个事件:

$('.BC1').live('click', function() {
    alert("clicked");
    $(this).closest('.portlet_10').find('.portlet_sub_header_10').empty();  
    get_firm_summary( $(this) );
});

警告并找到最近的portlet_sub_header_10并将其设置为empty();,因为插入的.BC1消失了。我遇到了get_firm_summary( $(this) );

的问题

该功能如下所示:

function get_firm_summary( that ) {
    $.ajax({
        url: 'get_firm_summary.aspx?rand=' + Math.random(),
        type: 'GET',
        error: function(xhr, status, error) {
            console.log(status);
            console.log(xhr.responseText);
        },
        success: function(results) { 
            console.log( that.attr("class") );
            that.closest('.portlet_10').find('.portlet_content_10').empty().append( results );
        }
    });
}

这里console.log工作正常,但portlet_content_10没有任何反应。

任何人都知道为什么会这样吗?

2 个答案:

答案 0 :(得分:1)

问题是因为在你调用get_firm_summary( $(this) );之前,你在被点击元素的父div上调用了empty()。这会丢失对DOM中元素的引用,从而无法呈现任何遍历函数。

试试这个:

$('.BC1').live('click', function() {
    get_firm_summary( $(this) );
});

// ajax:
success: function(results) {
    // add new text
    that.closest('.portlet_10').find('.portlet_content_10').empty().append("FOO BAR");

    // remove clicked element
    that.closest('.portlet_10').find('.portlet_sub_header_10').empty();  
}

查看working example

的小提琴

答案 1 :(得分:0)

试试这个以获得更好的解决方案

$('.BC1').live('click', function() {
    alert("clicked");
    get_firm_summary( $(this) );
    $(this).closest('.portlet_10').find('.portlet_sub_header_10').empty();  

});
相关问题