【问题标题】:Having difficulty with find/closest难以找到/最近
【发布时间】:2012-05-29 09:34:08
【问题描述】:

更新 1:

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

原始问题:

我已经重新开始了这个问题,因为它的结构不好并且引起了很多混乱。

在开始之前,我想指出我使用的是 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 没有任何反应。

有人知道为什么会这样吗?

【问题讨论】:

  • portlet_content_10 是空的还是完全没有变化?
  • @mgraph,portlet_content_10 中没有任何变化,因此它不会为空或根本没有变化。
  • @mgraph,我如何检查跟踪(结果),我以前从未使用过。
  • 对不起,我的意思是 console.log(results); trace 是用于闪存
  • @mgraph, console.log( results ); 返回我希望它插入到.portlet_content_10 中的所有内容。

标签: jquery jquery-ui jquery-selectors


【解决方案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

【讨论】:

  • 就是这样,即过早删除 span 标签。谢谢。
【解决方案2】:

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

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

});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-23
    • 1970-01-01
    • 2011-02-22
    • 2014-04-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多