JQuery最近的类选择

时间:2014-11-06 22:47:28

标签: javascript jquery html

我的布局如下(简化)

<div>
    <div class="msgOutput" id="msg2"></div>
    <form>
        <table>
            <tbody>
                <tr>
                    <td>
                        <p><input type="file" class="documentFile" id="documentFile2" /></p>
                    </td>
                </tr>
                ... more code here ...
            </tbody>
        </table>
    </form>
</div>

div.msgOutput更改(页面上有多个副本)时,我想在input.documentFile中添加一些内容

还有更多代码,所以我确实需要搜索最接近的class="msgOutput"

我知道这与closest()parent()或某事有关,但它不起作用:/

到目前为止,我尝试过这样的事情:

$('.documentFile').change(function(e){
    ....
    $($(this).attr('id')).parent().children('.msgOutput').attr('id').append('Hello World');
    $(this).closest('div').find('.msgOutput').append('Hello World');
    $(this).closest('div').sibling('.msgOutput').append('Hello World');
    ....
});

但它不起作用:(。任何人都有任何想法吗?

2 个答案:

答案 0 :(得分:1)

我建议这样的事情:http://jsfiddle.net/cr94dtk0/

您应该在包含div的位置放置一个类或id,以便您可以执行一些DOM Traversal

<div class="container">
<div class="msgOutput" id="msg2">hi</div>
<form>
    <table>
        <tbody>
            <tr>
                <td>
                    <p><input type="file" class="documentFile" id="documentFile2" /></p>
                </td>
            </tr>
        </tbody>
    </table>
</form>

  $(".documentFile").change(function(){
  $(this).closest(".container").find(".msgOutput").text("TEXT GOES HERE");
});

答案 1 :(得分:0)

您已经找到了最接近的div,但您正在添加额外的选择器方法,这会阻碍您的结果。

这有效:

$(this).closest('div').append('Hello World'); 
相关问题