【问题标题】:jQuery selecting returns undefinedjQuery选择返回未定义
【发布时间】:2014-10-29 14:05:47
【问题描述】:

我不确定为什么会发生这种情况,我列出了两种方式,一种是代码有效,另一种无效。 如果可能的话,我想用 THIS 获取 EACH 内部的值,以便我可以更改该值,但我可以从外部选择它们,为所有 IMG 做一个 each,这使我失去了与该相关联的 TD 的参考图片。

http://jsfiddle.net/4w8030th/1/

// Cannot retrieve SRC inside IMG tag
$.each($('tr.infraTrClara'), function () {
    // Post-It
    var postit = $(this).children('td:nth-child(2)').select('img');
    postit_src = $(postit).attr('src');
    alert(postit_src);
});

// Can retrieve SRC inside IMG tag
$.each($('tr.infraTrClara td:nth-child(2) img'), function () {
    // Post-It
    var postit = $(this).attr('src');
    alert(postit);
});

【问题讨论】:

  • .select 更改为.find

标签: javascript jquery jquery-selectors this attr


【解决方案1】:

.select()是一种事件监听绑定方法,类似于.click()。你可能想要一个.children() 来实现相同的行为。

【讨论】:

    【解决方案2】:

    适合这种情况的方法是.find(),而不是.children().select()

    然后,由于它将是一个多重结果,而不是将其设置为变量,也对其执行.each()

    http://jsfiddle.net/4w8030th/3/

    $.each($('tr.infraTrClara'), function () {
        // Post-It
        $(this).find('td:nth-child(2)').find('img').each(function() {
            postit_src = $(this).attr('src');
            alert(postit_src);
        });
    });
    

    编辑

    凯文在 cmets 上提出了一个很好的观点。我假设您需要一个与您发布的第二个代码不同的解决方案(即有效),还有一个原因......

    但是,你提到你不想

    丢失与该 IMG 关联的 TD 的引用。

    所以,如果您只想操作td,请使用您的第二个代码并使用parent() 调用它:

    $.each($('tr.infraTrClara td:nth-child(2) img'), function () {
        // Post-It
        var postit = $(this).attr('src');
        alert(postit);
    
        var td = $(this).parent(); //HERE!!!
    });
    

    【讨论】:

    • 为什么find比children更适合?他是否在某个地方包含了 html,表明他在单元格中不仅仅是一个 img?我认为他自己的第二次尝试比使用 find 或 children 更好。
    • 可能我表达的不对……合适不是这个词,但是findchildren快。 stackoverflow.com/questions/648004/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-24
    • 2018-10-19
    • 2020-08-31
    • 2011-04-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多